use BARPOS
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_CARI_MAIN') AND name='EMAIL')
ALTER TABLE dbo.TBL_CARI_MAIN ADD
	EMAIL varchar(MAX) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_CARI_MAIN') AND name='TELEFON')
ALTER TABLE dbo.TBL_CARI_MAIN ADD
	TELEFON varchar(20) NULL
GO

SET IDENTITY_INSERT [dbo].[TBL_YETKI_TANIM] ON

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'CLSWIN')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (22, N'CLSWIN', N'Bilgisayarı Kapatma')

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'CLSBSF')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (23, N'CLSBSF', N'Programdan Çıkış')

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'RSTBSF')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (24, N'RSTBSF', N'Barposu Tekrar Başlatma')

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'CRDRDR')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (25, N'CRDRDR', N'Müşteri Kartı Manuel Giriş')

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'YVRLMA')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (26, N'YVRLMA', N'Yuvarlama İşlemi')

SET IDENTITY_INSERT [dbo].[TBL_YETKI_TANIM] OFF
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='DOVIZKODU')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	DOVIZKODU varchar(10) NULL
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_DOVIZ]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_DOVIZ](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[DOVIZKODU] [varchar](10) NOT NULL,
		[DOVIZKURU] [float] NOT NULL,
		[CHANGEDATE] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_DOVIZ] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO


IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_DETAY') AND name='DOVIZKODU')
ALTER TABLE dbo.TBL_FIS_DETAY ADD
	DOVIZKODU varchar(10) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_DETAY') AND name='DOVIZKURU')
ALTER TABLE dbo.TBL_FIS_DETAY ADD
	DOVIZKURU float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_DETAY') AND name='DOVIZTUTARI')
ALTER TABLE dbo.TBL_FIS_DETAY ADD
	DOVIZTUTARI float(53) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_ODEME') AND name='DOVIZKODU')
ALTER TABLE dbo.TBL_FIS_ODEME ADD
	DOVIZKODU varchar(10) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_ODEME') AND name='DOVIZKURU')
ALTER TABLE dbo.TBL_FIS_ODEME ADD
	DOVIZKURU float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_ODEME') AND name='DOVIZTUTARI')
ALTER TABLE dbo.TBL_FIS_ODEME ADD
	DOVIZTUTARI float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_DETAY') AND name='DOVIZKODU')
ALTER TABLE dbo.TBL_BEKLETME_DETAY ADD
	DOVIZKODU varchar(10) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_DETAY') AND name='DOVIZKURU')
ALTER TABLE dbo.TBL_BEKLETME_DETAY ADD
	DOVIZKURU float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_DETAY') AND name='DOVIZTUTARI')
ALTER TABLE dbo.TBL_BEKLETME_DETAY ADD
	DOVIZTUTARI float(53) NULL
GO



IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_URUN') AND name='PUAN')
ALTER TABLE dbo.TBL_PROMOSYON_URUN ADD
	PUAN float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_TUTAR') AND name='PUAN')
ALTER TABLE dbo.TBL_PROMOSYON_TUTAR ADD
	PUAN float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_REYON') AND name='PUAN')
ALTER TABLE dbo.TBL_PROMOSYON_REYON ADD
	PUAN float(53) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_MAIN') AND name='PUAN')
ALTER TABLE dbo.TBL_FIS_MAIN ADD
	PUAN float(53) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_MAIN') AND name='ISSENDPUAN')
ALTER TABLE dbo.TBL_FIS_MAIN ADD
	ISSENDPUAN bit NULL
GO


IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='ALISDEPARTMAN')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	ALISDEPARTMAN int NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='ALISKDV')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	ALISKDV float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_CARI_MAIN') AND name='CARITIPI')
ALTER TABLE dbo.TBL_CARI_MAIN ADD
	CARITIPI varchar(1) NULL
GO



		

		

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_STOK_KOD]') AND type in (N'U'))
	CREATE TABLE [dbo].[TBL_STOK_KOD](
		[BARKOD] [varchar](20) NOT NULL,
		[STOKKODU] [varchar](50) NOT NULL
	) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_STOK_KOD]') AND name = N'IX_TBL_STOK_KOD')
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_STOK_KOD] ON [dbo].[TBL_STOK_KOD] 
	(
		[BARKOD] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO







IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_PROMOSYON') AND name='KREDINO')
ALTER TABLE dbo.TBL_FIS_PROMOSYON ADD
	KREDINO int NULL
GO


IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_MAIN') AND name='ACIKLAMA')
ALTER TABLE dbo.TBL_FIS_MAIN ADD
	ACIKLAMA varchar(max) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_DETAY') AND name='PUAN')
ALTER TABLE dbo.TBL_BEKLETME_DETAY ADD
	PUAN float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_DETAY') AND name='PUAN')
ALTER TABLE dbo.TBL_FIS_DETAY ADD
	PUAN float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_URUN') AND name='CARIGRUP')
ALTER TABLE dbo.TBL_PROMOSYON_URUN ADD
	CARIGRUP varchar(20) NULL
GO





IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[APPSTRIPNONEMAIL]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[APPSTRIPNONEMAIL]
GO
CREATE FUNCTION [dbo].[APPSTRIPNONEMAIL](@TEMP VARCHAR(1000))
RETURNS VARCHAR(1000)
AS
BEGIN

    DECLARE @KEEPVALUES AS VARCHAR(50)
    SET @KEEPVALUES = '%[^a-z,0-9,-,@,.,-,_]%'
    WHILE (PATINDEX(@KEEPVALUES, @TEMP) > 0) OR (CHARINDEX('-', @TEMP) > 0)
        SET @TEMP = STUFF(@TEMP, PATINDEX(@KEEPVALUES, @TEMP), 1, '')

    RETURN @TEMP
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CHECKEMAILFORMAT]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[CHECKEMAILFORMAT]
GO

CREATE FUNCTION [dbo].[CHECKEMAILFORMAT](@EMAIL VARCHAR(255))   
RETURNS BIT  
AS  
BEGIN  
     DECLARE @VALID BIT  
     IF @EMAIL IS NOT NULL   
          SET @EMAIL = LOWER(@EMAIL)  
          SET @VALID = 0  
          IF @EMAIL LIKE '[a-z,0-9,''_'',-]%@[a-z,0-9,_,-]%.[a-z][a-z]%'  
             AND LEN(REPLACE(@EMAIL,'-','')) = LEN(DBO.APPSTRIPNONEMAIL(@EMAIL))  
             AND @EMAIL NOT LIKE '%@%@%'  
             AND CHARINDEX('.@',@EMAIL) = 0  
             AND CHARINDEX('..',@EMAIL) = 0  
             AND CHARINDEX(',',@EMAIL) = 0  
             AND RIGHT(@EMAIL,1) BETWEEN 'a' AND 'z'  
               SET @VALID=1  
     RETURN @VALID  
END  

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_FIS_SLIP]') AND type in (N'U'))
	CREATE TABLE [dbo].[TBL_FIS_SLIP](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[FISID] [int] NOT NULL,
		[DATA] [varchar](max) NOT NULL,
	 CONSTRAINT [PK_TBL_FIS_SLIP] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
GO


IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_FIS_SLIP]') AND name = N'IX_TBL_FIS_SLIP')
	CREATE NONCLUSTERED INDEX [IX_TBL_FIS_SLIP] ON [dbo].[TBL_FIS_SLIP] 
	(
		[FISID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_FIS_SLIP]') AND name = N'PK_TBL_FIS_SLIP')
	ALTER TABLE [dbo].[TBL_FIS_SLIP] ADD  CONSTRAINT [PK_TBL_FIS_SLIP] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
GO


ALTER TRIGGER [dbo].[TRG_FIS_MAIN_INSTEADOF_DELETE]
ON  [dbo].[TBL_FIS_MAIN]
INSTEAD OF DELETE
AS
BEGIN
	SET NOCOUNT ON;

	DELETE FROM TBL_FIS_DETAY		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_ODEME		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_PROMOSYON	WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_LOG			WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_SLIP		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_MAIN		WHERE ID IN (SELECT ID FROM DELETED)

END
GO









IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_MAIN') AND name='YETKILIKODU')
ALTER TABLE dbo.TBL_FIS_MAIN ADD
	YETKILIKODU varchar(4) NULL,
	YETKILIADI varchar(50) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_MAIN') AND name='YETKILIKODU')
ALTER TABLE dbo.TBL_BEKLETME_MAIN ADD
	YETKILIKODU varchar(4) NULL,
	YETKILIADI varchar(50) NULL
GO








IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETLASTBARKOD]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GETLASTBARKOD]
GO
CREATE FUNCTION [dbo].[GETLASTBARKOD](@PLUNO INT)
RETURNS VARCHAR(20)
AS
BEGIN
	DECLARE @RETVALUE VARCHAR(20)

	SELECT 
		TOP 1
		@RETVALUE = M.BARKOD
	FROM TBL_STOK_MAIN M WITH (NOLOCK) 
	WHERE PLUNO = @PLUNO
	ORDER BY M.ID DESC
	
	RETURN ISNULL(@RETVALUE,'')
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GETPARAMS]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[GETPARAMS]
GO
CREATE FUNCTION [dbo].[GETPARAMS](@PARAMS VARCHAR(MAX))
RETURNS @RETTABLE TABLE (CODE INT )
AS
BEGIN
DECLARE 
	@INDEX INT,
	@CODE  INT,
	@TMPPARAMS   VARCHAR(MAX),
	@COUNT INT

DECLARE
	@IDTABLE TABLE ( CODE INT )

SET @TMPPARAMS = ISNULL(@PARAMS,'')

IF LEN(LTRIM(RTRIM(@TMPPARAMS))) = 0 
BEGIN
	INSERT INTO @RETTABLE (CODE)
	SELECT  0 
	RETURN
END

WHILE 1 <> 2 
BEGIN
	SELECT @INDEX = CHARINDEX(',', @TMPPARAMS)
	IF @INDEX = 0
	BEGIN
		SELECT @COUNT = COUNT(*) 
		FROM @IDTABLE 
		WHERE CODE = @TMPPARAMS

		SET @COUNT = ISNULL(@COUNT,0)
		
		IF @COUNT = 0 
			INSERT INTO @IDTABLE(CODE)
			SELECT CONVERT(INT, @TMPPARAMS)

		BREAK		
	END

	SELECT @CODE = CONVERT(INT, SUBSTRING(@TMPPARAMS, 1, @INDEX - 1))
	SELECT @TMPPARAMS = STUFF(@TMPPARAMS, 1, @INDEX, '')
	
	SELECT @COUNT = COUNT(*) 
	FROM @IDTABLE 
	WHERE CODE = @CODE
	
	SET @COUNT = ISNULL(@COUNT,0)
	
	IF @COUNT = 0 
		INSERT INTO @IDTABLE(CODE)
		SELECT @CODE
END
	INSERT INTO @RETTABLE (CODE)
	SELECT CODE FROM @IDTABLE

	RETURN
END
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='RENK')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	RENK varchar(50) NULL,
	BEDEN varchar(20) NULL,
	MODELKODU varchar(20) NULL
GO
UPDATE TBL_STOK_MAIN
SET RENK = '',
	BEDEN = '',
	MODELKODU = ''
WHERE RENK IS NULL
GO
	
		

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_PLATFORM_STATUS]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS_PLATFORM_STATUS](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BELGEID] [int] NOT NULL,
		[ORDERSTATE] [tinyint] NOT NULL,
		[STATEDATE] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_SIPARIS_PLATFORM_STATUS] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_PLATFORM_DETAY]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS_PLATFORM_DETAY](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BELGEID] [int] NOT NULL,
		[PRODUCTID] [varchar](50) NOT NULL,
		[NAME] [varchar](255) NOT NULL,
		[PRICE] [money] NOT NULL,
		[LISTPRICE] [money] NOT NULL,
		[QUANTITY] [money] NOT NULL,
		[ORDERINDEX] [int] NOT NULL,
		[CREATEDATE] [datetime] NOT NULL,
		[CHANGEDATE] [datetime] NULL,
	 CONSTRAINT [PK_TBL_SIPARIS_PLATFORM_DETAY] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_PLATFORM_MAIN]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS_PLATFORM_MAIN](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[PLATFORMTYPE] [tinyint] NOT NULL,
		[ORDERID] [varchar](50) NOT NULL,
		[MESSAGEID] [int] NULL,
		[RESTAURANTNAME] [varchar](255) NOT NULL,
		[CUSTOMERNAME] [varchar](255) NOT NULL,
		[PAYMENTNOTE] [varchar](max) NULL,
		[ORDERTOTAL] [money] NOT NULL,
		[CUSTOMERPHONE] [varchar](50) NOT NULL,
		[CUSTOMERPHONE2] [varchar](50) NULL,
		[PROMOCODE] [varchar](50) NULL,
		[CITY] [varchar](50) NULL,
		[REGION] [varchar](50) NULL,
		[ORGANIZATION] [varchar](255) NULL,
		[ADDRESS] [varchar](max) NULL,
		[ADDRESSDESCIPTION] [varchar](max) NULL,
		[PAYMENTMETHODID] [int] NOT NULL,
		[DELIVERYTIME] [datetime] NOT NULL,
		[CHANGEINTOTAL] [money] NULL,
		[ORDERNOTE] [varchar](max) NULL,
		[ORDERSTATE] [tinyint] NOT NULL,
		[KURYEADI] [varchar](50) NULL,
		[POSFISID] [int] NULL,
		[CREATEDATE] [datetime] NOT NULL,
		[CHANGEDATE] [datetime] NULL,
	 CONSTRAINT [PK_TBL_SIPARIS_PLATFORM_MAIN] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_PLATFORM_OPTION]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS_PLATFORM_OPTION](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[DETAYID] [int] NOT NULL,
		[OPTIONID] [varchar](50) NOT NULL,
		[NAME] [varchar](255) NOT NULL,
	 CONSTRAINT [PK_TBL_SIPARIS_PLATFORM_OPTION] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO











IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_SIPARIS_PLATFORM_MAIN') AND name='POSID')
ALTER TABLE dbo.TBL_SIPARIS_PLATFORM_MAIN ADD
	POSID INT NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_SIPARIS_PLATFORM_MAIN') AND name='TERMINALNO')
ALTER TABLE dbo.TBL_SIPARIS_PLATFORM_MAIN ADD
	TERMINALNO VARCHAR(20) NULL
GO

















IF  EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[TRG_SIPARIS_PLATFORM_MAIN_INSTEADOF_DELETE]'))
DROP TRIGGER [dbo].[TRG_SIPARIS_PLATFORM_MAIN_INSTEADOF_DELETE]
GO

CREATE TRIGGER TRG_SIPARIS_PLATFORM_MAIN_INSTEADOF_DELETE 
   ON  TBL_SIPARIS_PLATFORM_MAIN 
   INSTEAD OF DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	
	DELETE FROM TBL_SIPARIS_PLATFORM_OPTION 
	WHERE DETAYID IN (SELECT ID FROM TBL_SIPARIS_PLATFORM_DETAY WHERE BELGEID IN (SELECT ID FROM DELETED))
	
	DELETE FROM TBL_SIPARIS_PLATFORM_DETAY
	WHERE BELGEID IN (SELECT ID FROM DELETED)

	DELETE FROM TBL_SIPARIS_PLATFORM_MAIN
	WHERE ID IN (SELECT ID FROM DELETED)
END
GO




IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_REYON') AND name='ISKADEMELI')
ALTER TABLE dbo.TBL_PROMOSYON_REYON ADD
	ISKADEMELI bit NULL
GO


IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_TUTAR') AND name='TUMURUNLER')
ALTER TABLE dbo.TBL_PROMOSYON_TUTAR ADD
	TUMURUNLER bit NULL
GO

UPDATE TBL_PROMOSYON_TUTAR
SET TUMURUNLER = 0
WHERE TUMURUNLER IS NULL
GO








IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_PLATFORM_PAYMENT]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS_PLATFORM_PAYMENT](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BELGEID] [int] NOT NULL,
		[ODEMETIPI] [int] NOT NULL,
		[TAKSITSAYISI] [int] NOT NULL,
		[KREDINO] [int] NOT NULL,
		[BKMNO] [varchar](20) NOT NULL,
		[TUTAR] [float] NOT NULL,
		[ACIKLAMA] [varchar](max) NOT NULL,
		[KARTNO] [varchar](50) NOT NULL,
		[CREATEDATE] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_SIPARIS_PLATFORM_PAYMENT] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] 


	CREATE NONCLUSTERED INDEX [IX_TBL_SIPARIS_PLATFORM_PAYMENT] ON [dbo].[TBL_SIPARIS_PLATFORM_PAYMENT]
	(
		[BELGEID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	ALTER TABLE [dbo].[TBL_SIPARIS_PLATFORM_PAYMENT]  WITH CHECK ADD  CONSTRAINT [FK_TBL_SIPARIS_PLATFORM_PAYMENT_TBL_SIPARIS_PLATFORM_MAIN] FOREIGN KEY([BELGEID])
	REFERENCES [dbo].[TBL_SIPARIS_PLATFORM_MAIN] ([ID])
	
	ALTER TABLE [dbo].[TBL_SIPARIS_PLATFORM_PAYMENT] CHECK CONSTRAINT [FK_TBL_SIPARIS_PLATFORM_PAYMENT_TBL_SIPARIS_PLATFORM_MAIN]
END
GO


ALTER TRIGGER [dbo].[TRG_SIPARIS_PLATFORM_MAIN_INSTEADOF_DELETE] 
   ON  [dbo].[TBL_SIPARIS_PLATFORM_MAIN] 
   INSTEAD OF DELETE
AS 
BEGIN
	SET NOCOUNT ON;
	
	DELETE FROM TBL_SIPARIS_PLATFORM_OPTION 
	WHERE DETAYID IN (SELECT ID FROM TBL_SIPARIS_PLATFORM_DETAY WHERE BELGEID IN (SELECT ID FROM DELETED))
	
	DELETE FROM TBL_SIPARIS_PLATFORM_DETAY
	WHERE BELGEID IN (SELECT ID FROM DELETED)

	DELETE FROM TBL_SIPARIS_PLATFORM_PAYMENT
	WHERE BELGEID IN (SELECT ID FROM DELETED)

	DELETE FROM TBL_SIPARIS_PLATFORM_MAIN
	WHERE ID IN (SELECT ID FROM DELETED)
END
GO






IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='STOKKODU')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	STOKKODU varchar(20) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_URUN') AND name='STOKKODU')
ALTER TABLE dbo.TBL_PROMOSYON_URUN ADD
	STOKKODU varchar(20) NULL,
	VSTOKKODU varchar(20) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_TUTAR') AND name='VSTOKKODU')
ALTER TABLE dbo.TBL_PROMOSYON_TUTAR ADD
	VSTOKKODU varchar(20) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_REYON') AND name='VSTOKKODU')
ALTER TABLE dbo.TBL_PROMOSYON_REYON ADD
	VSTOKKODU varchar(20) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_DETAY') AND name='STOKKODU')
ALTER TABLE dbo.TBL_FIS_DETAY ADD
	STOKKODU varchar(20) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_DETAY') AND name='STOKKODU')
ALTER TABLE dbo.TBL_BEKLETME_DETAY ADD
	STOKKODU varchar(20) NULL
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_STOK_MAIN]') AND name = N'IX_TBL_STOK_MAIN_1')
CREATE NONCLUSTERED INDEX IX_TBL_STOK_MAIN_1 ON dbo.TBL_STOK_MAIN
	(
	STOKKODU
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO































IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TIP] [tinyint] NOT NULL,
		[TARIH] [datetime] NOT NULL,
		[TELEFON] [varchar](20) NOT NULL,
		[ADSOYAD] [varchar](255) NOT NULL,
		[ADRES] [varchar](1000) NOT NULL,
		[ACIKLAMA] [varchar](max) NOT NULL,
		[SEPETID] [varchar](50) NOT NULL,
		[TUTAR] [float] NOT NULL,
		[KURYEADI] [varchar](50) NULL,
		[KURYECAGIRILDI] [bit] NOT NULL,
		[ODEMESEKLI] [tinyint] NOT NULL,
		[DURUM] [tinyint] NOT NULL,
		[DURUMTARIHI] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_SIPARIS] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_KURYE]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_KURYE](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[AKTIF] [bit] NOT NULL,
		[KURYEADI] [varchar](50) NOT NULL,
		[TELEFON] [varchar](20) NOT NULL,
		[PRIMYUZDE] [decimal](4, 2) NOT NULL,
	 CONSTRAINT [PK_TBL_KURYE] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_MESAJ]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_MESAJ](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[MESAJID] [varchar](50) NOT NULL,
		[KIMDEN] [varchar](20) NOT NULL,
		[KIME] [varchar](20) NOT NULL,
		[MESAJ] [varchar](max) NOT NULL,
		[DURUM] [tinyint] NOT NULL,
		[TARIH] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_MESAJ] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_CARI_ADRES]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_CARI_ADRES](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[CARIKODU] [varchar](20) NOT NULL,
		[AKTIF] [bit] NOT NULL,
		[ADRES] [varchar](1000) NOT NULL,
		[LATITUDE] [varchar](20) NULL,
		[LONGITUDE] [varchar](20) NULL,
	 CONSTRAINT [PK_TBL_CARI_ADRES] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SUBE]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SUBE](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[MERKEZ] [bit] NOT NULL,
		[SUBEKODU] [varchar](20) NOT NULL,
		[YETKILI] [varchar](20) NOT NULL,
		[TELEFON] [varchar](20) NOT NULL,
	 CONSTRAINT [PK_TBL_SUBE] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SUBE_CARI]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SUBE_CARI](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[SUBEID] [int] NOT NULL,
		[CARIKODU] [varchar](20) NOT NULL,
	 CONSTRAINT [PK_TBL_SUBE_CARI] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_CARI_TELEFON]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_CARI_TELEFON](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[CARIKODU] [varchar](20) NOT NULL,
		[TELEFON] [varchar](20) NOT NULL,
	 CONSTRAINT [PK_TBL_CARI_TELEFON] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_DETAY]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS_DETAY](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[SIPARISID] [int] NOT NULL,
		[BARKOD] [varchar](20) NOT NULL,
		[URUNADI] [varchar](255) NOT NULL,
		[MIKTAR] [float] NOT NULL,
		[BIRIM] [varchar](10) NOT NULL,
		[FIYAT] [float] NOT NULL,
		[TUTAR] [float] NOT NULL
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SEPET]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SEPET](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[SEPETID] [varchar](50) NOT NULL,
		[TELEFON] [varchar](20) NOT NULL,
		[BARKOD] [varchar](20) NOT NULL,
		[MIKTAR] [float] NOT NULL,
		[BIRIM] [varchar](10) NOT NULL,
		[FIYAT] [float] NOT NULL,
		[TUTAR] [float] NOT NULL,
		[TARIH] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_SEPET] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_HAZIR_MESAJ]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_HAZIR_MESAJ](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[KISAYOL] [varchar](1) NOT NULL,
		[MESAJ] [varchar](max) NOT NULL,
	 CONSTRAINT [PK_TBL_HAZIR_MESAJ] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_KURYE]') AND name = N'IX_TBL_KURYE')
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_KURYE] ON [dbo].[TBL_KURYE]
	(
		[KURYEADI] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_MESAJ]') AND name = N'IX_TBL_MESAJ')
	CREATE NONCLUSTERED INDEX [IX_TBL_MESAJ] ON [dbo].[TBL_MESAJ]
	(
		[KIMDEN] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_MESAJ]') AND name = N'IX_TBL_MESAJ_1')
	CREATE NONCLUSTERED INDEX [IX_TBL_MESAJ_1] ON [dbo].[TBL_MESAJ]
	(
		[KIME] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_MESAJ]') AND name = N'IX_TBL_MESAJ_2')
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_MESAJ_2] ON [dbo].[TBL_MESAJ]
	(
		[MESAJID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_CARI_ADRES]') AND name = N'IX_TBL_CARI_ADRES')
	CREATE NONCLUSTERED INDEX [IX_TBL_CARI_ADRES] ON [dbo].[TBL_CARI_ADRES]
	(
		[CARIKODU] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SUBE]') AND name = N'IX_TBL_SUBE')
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_SUBE] ON [dbo].[TBL_SUBE]
	(
		[SUBEKODU] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SUBE_CARI]') AND name = N'IX_TBL_SUBE_CARI')
	CREATE NONCLUSTERED INDEX [IX_TBL_SUBE_CARI] ON [dbo].[TBL_SUBE_CARI]
	(
		[SUBEID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SUBE_CARI]') AND name = N'IX_TBL_SUBE_CARI_1')
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_SUBE_CARI_1] ON [dbo].[TBL_SUBE_CARI]
	(
		[CARIKODU] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_CARI_TELEFON]') AND name = N'IX_TBL_CARI_TELEFON')
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_CARI_TELEFON] ON [dbo].[TBL_CARI_TELEFON]
	(
		[CARIKODU] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_CARI_TELEFON]') AND name = N'IX_TBL_CARI_TELEFON_1')
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_CARI_TELEFON_1] ON [dbo].[TBL_CARI_TELEFON]
	(
		[TELEFON] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_DETAY]') AND name = N'IX_TBL_SIPARIS_DETAY')
	CREATE NONCLUSTERED INDEX [IX_TBL_SIPARIS_DETAY] ON [dbo].[TBL_SIPARIS_DETAY]
	(
		[SIPARISID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SEPET]') AND name = N'IX_TBL_SEPET')
	CREATE NONCLUSTERED INDEX [IX_TBL_SEPET] ON [dbo].[TBL_SEPET]
	(
		[TELEFON] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SEPET]') AND name = N'IX_TBL_SEPET_1')
	CREATE NONCLUSTERED INDEX [IX_TBL_SEPET_1] ON [dbo].[TBL_SEPET]
	(
		[BARKOD] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * 
  FROM sys.foreign_keys 
   WHERE object_id = OBJECT_ID(N'dbo.FK_TBL_SUBE_CARI_TBL_SUBE')
   AND parent_object_id = OBJECT_ID(N'dbo.TBL_SUBE_CARI')
)
	ALTER TABLE [dbo].[TBL_SUBE_CARI]  WITH CHECK ADD  CONSTRAINT [FK_TBL_SUBE_CARI_TBL_SUBE] FOREIGN KEY([SUBEID])
	REFERENCES [dbo].[TBL_SUBE] ([ID])
GO

ALTER TABLE [dbo].[TBL_SUBE_CARI] CHECK CONSTRAINT [FK_TBL_SUBE_CARI_TBL_SUBE]
GO

IF NOT EXISTS (SELECT * 
  FROM sys.foreign_keys 
   WHERE object_id = OBJECT_ID(N'dbo.FK_TBL_SIPARIS_DETAY_TBL_SIPARIS')
   AND parent_object_id = OBJECT_ID(N'dbo.TBL_SIPARIS_DETAY')
)
	ALTER TABLE [dbo].[TBL_SIPARIS_DETAY]  WITH CHECK ADD  CONSTRAINT [FK_TBL_SIPARIS_DETAY_TBL_SIPARIS] FOREIGN KEY([SIPARISID])
	REFERENCES [dbo].[TBL_SIPARIS] ([ID])
GO

ALTER TABLE [dbo].[TBL_SIPARIS_DETAY] CHECK CONSTRAINT [FK_TBL_SIPARIS_DETAY_TBL_SIPARIS]
GO










































SELECT ID, CARIKODU, REPLACE(TELEFON,' ','') AS TELEFON, CONVERT(BIT, 0) AS ISDELETE INTO #TMP 
FROM TBL_CARI_MAIN WITH (NOLOCK)
WHERE LEN(REPLACE(TELEFON,' ','')) >= 10 

UPDATE #TMP
SET TELEFON = CASE WHEN SUBSTRING(TELEFON,1,2) = '05' THEN '9'+TELEFON WHEN SUBSTRING(TELEFON,1,1) = '5' THEN '90'+TELEFON ELSE TELEFON END

UPDATE #TMP
SET ISDELETE = 1
FROM #TMP C
	INNER JOIN TBL_CARI_TELEFON T WITH (NOLOCK) ON T.CARIKODU = C.CARIKODU AND T.TELEFON = C.TELEFON

DELETE FROM #TMP
WHERE ISDELETE = 1

INSERT INTO TBL_CARI_TELEFON(CARIKODU, TELEFON)
SELECT CARIKODU, TELEFON FROM #TMP
WHERE ID IN (
				SELECT MAX(ID) FROM #TMP
				WHERE 
					TELEFON LIKE '905%' AND
					LEN(TELEFON) = 12 AND
					TELEFON NOT LIKE '%[a-z][A-Z]%'
				GROUP BY TELEFON
			) AND TELEFON NOT IN (SELECT TELEFON FROM TBL_CARI_TELEFON WITH (NOLOCK))

DROP TABLE #TMP
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[utf8_to_utf16]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[utf8_to_utf16]
GO
CREATE FUNCTION dbo.utf8_to_utf16 (@s varchar(8000))
RETURNS nvarchar(4000)
BEGIN
  IF @s IS NULL RETURN NULL
  DECLARE @n int, @r nvarchar(4000), @cn int, @octets int, @ch nvarchar(2)
  SET @r = N''
  WHILE 1 = 1 BEGIN
    -- dubious: unexpected octets (0x80-0xBF, 0xF8-0xFF) are treated like 0x00-0x7F
    SET @n = PATINDEX('%[À-÷]%', @s COLLATE Latin1_General_bin)
    IF @n = 0 BEGIN
      SET @r = @r + @s
      BREAK
    END ELSE BEGIN
      SET @r = @r + SUBSTRING(@s, 1, @n-1)
      SET @cn = ASCII(SUBSTRING(@s, @n, 1))
      IF @cn <= 0xDF BEGIN
        SET @octets = 2
        SET @ch = NCHAR((@cn & 0x1F) * 0x40 +
          (ASCII(SUBSTRING(@s, @n+1, 1)) & 0x3F))
      END ELSE IF @cn <= 0xEF BEGIN
        SET @octets = 3
        SET @ch = NCHAR((@cn & 0x0F) * 0x1000 +
          (ASCII(SUBSTRING(@s, @n+1, 1)) & 0x3F) * 0x40 +
          (ASCII(SUBSTRING(@s, @n+2, 1)) & 0x3F))
      END ELSE BEGIN
        -- code point in a supplementary plane: output UTF-16 surrogate pair
        SET @octets = 4
        SET @ch = NCHAR((@cn & 0x07) * 0x100 + 
            (ASCII(SUBSTRING(@s, @n+1, 1)) & 0x3F) * 0x04 +
            (ASCII(SUBSTRING(@s, @n+2, 1)) & 0x30) / 0x10 + 0xD7C0) +
          NCHAR((ASCII(SUBSTRING(@s, @n+2, 1)) & 0x0F) * 0x40 +
            (ASCII(SUBSTRING(@s, @n+3, 1)) & 0x3F) + 0xDC00)
      END
      SET @r = @r + @ch
      SET @s = SUBSTRING(@s, @n+@octets, 8000)
    END
  END
  RETURN @r
END
GO


DROP INDEX IX_TBL_CARI_EFATURA ON dbo.TBL_CARI_EFATURA
GO
CREATE NONCLUSTERED INDEX IX_TBL_CARI_EFATURA ON dbo.TBL_CARI_EFATURA
	(
	ALIAS,
	IDENTIFIER
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SMS_KONTROL]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SMS_KONTROL](
		[TELEFON] [varchar](20) NOT NULL,
		[SMSSIFRE] [varchar](6) NOT NULL,
		[CREATEDATE] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_SMS_KONTROL] PRIMARY KEY CLUSTERED 
	(
		[TELEFON] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO




IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_CALLER_ID]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_CALLER_ID](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[TELEFONNUMARASI] [varchar](20) NOT NULL,
		[TARIH] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_CALLER_ID] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO




IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_SIPARIS_TALEP_MAIN]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_SIPARIS_TALEP_MAIN](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[SIPARISID] [int] NOT NULL,
		[BELGEKODU] [varchar](20) NOT NULL,
		[CARIADI] [varchar](255) NOT NULL,
	 CONSTRAINT [PK_TBL_SIPARIS_TALEP_MAIN] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END





IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_KASA_TAKIP_FIS_MAIN]') AND type in (N'U'))
CREATE TABLE [dbo].[TBL_KASA_TAKIP_FIS_MAIN](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[TARIH] [datetime] NOT NULL,
	[KASANO] [int] NOT NULL,
	[KASIYERKODU] [varchar](100) NOT NULL,
	[KASIYERADI] [varchar](50) NOT NULL,
 CONSTRAINT [PK_TBL_KASA_TAKIP_FIS_MAIN] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_KASA_TAKIP_FIS_DETAY]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_KASA_TAKIP_FIS_DETAY](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BELGEID] [int] NOT NULL,
		[ACIKLAMA] [varchar](100) NOT NULL,
		[TIP] [int] NOT NULL,
		[TIPNO] [int] NOT NULL,
		[ADET] [int] NOT NULL,
		[TUTAR] [float] NOT NULL,
	 CONSTRAINT [PK_TBL_KASA_TAKIP_FIS_DETAY] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX [IX_TBL_KASA_TAKIP_FIS_DETAY] ON [dbo].[TBL_KASA_TAKIP_FIS_DETAY]
	(
		[BELGEID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	ALTER TABLE [dbo].[TBL_KASA_TAKIP_FIS_DETAY]  WITH CHECK ADD  CONSTRAINT [FK_TBL_KASA_TAKIP_FIS_DETAY_TBL_KASA_TAKIP_FIS_MAIN] FOREIGN KEY([BELGEID])
	REFERENCES [dbo].[TBL_KASA_TAKIP_FIS_MAIN] ([ID])

	ALTER TABLE [dbo].[TBL_KASA_TAKIP_FIS_DETAY] CHECK CONSTRAINT [FK_TBL_KASA_TAKIP_FIS_DETAY_TBL_KASA_TAKIP_FIS_MAIN]
END
GO







IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_ODEME') AND name='ISTICKET')
ALTER TABLE dbo.TBL_FIS_ODEME ADD
	ISTICKET bit NULL
GO

UPDATE TBL_FIS_ODEME
SET ISTICKET = 0
WHERE ISTICKET IS NULL
GO




		



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CHECKSUMKONTROL]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[CHECKSUMKONTROL]
GO
CREATE FUNCTION [CHECKSUMKONTROL](@BARKOD	VARCHAR(20), @UZUNLUK TINYINT)
RETURNS VARCHAR(MAX)
AS
BEGIN

DECLARE
	@MAXBARKOD		BIGINT,
	@RETBARKOD		VARCHAR(20)

	SET @RETBARKOD = NULL

	IF @UZUNLUK NOT IN (7,8,13)   SET @RETBARKOD = @BARKOD

	IF LEN(@BARKOD) >= @UZUNLUK SET @RETBARKOD = @BARKOD

	IF @UZUNLUK = 7	SET @RETBARKOD = @BARKOD

	IF @RETBARKOD IS NULL
	BEGIN
		DECLARE @ICOUNTER 	INT,
				@TOPLAM		INT


		SET @TOPLAM = 0
		SET @RETBARKOD = REVERSE(@BARKOD)
		SET @ICOUNTER = 1

		WHILE @ICOUNTER <= LEN(@RETBARKOD)
		BEGIN

			IF  @ICOUNTER % 2 = 1
				SET @TOPLAM = @TOPLAM + CONVERT(INT, SUBSTRING(@RETBARKOD, @ICOUNTER, 1)) * 3
			ELSE
				SET @TOPLAM = @TOPLAM + (CONVERT(INT, SUBSTRING(@RETBARKOD, @ICOUNTER, 1)) )

			SET @ICOUNTER = @ICOUNTER + 1
		END

		SET @RETBARKOD = @BARKOD + CONVERT(VARCHAR(1), ((10 - (@TOPLAM % 10)) % 10))
	END

	RETURN @RETBARKOD 
END
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_BOLGE]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_BOLGE](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BOLGEADI] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_TBL_BOLGE] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	SET IDENTITY_INSERT [dbo].[TBL_BOLGE] ON 
	INSERT [dbo].[TBL_BOLGE] ([ID], [BOLGEADI]) VALUES (1, N'MARMARA')
	INSERT [dbo].[TBL_BOLGE] ([ID], [BOLGEADI]) VALUES (2, N'EGE')
	INSERT [dbo].[TBL_BOLGE] ([ID], [BOLGEADI]) VALUES (3, N'AKDENİZ')
	INSERT [dbo].[TBL_BOLGE] ([ID], [BOLGEADI]) VALUES (4, N'G.D.ANADOLU')
	INSERT [dbo].[TBL_BOLGE] ([ID], [BOLGEADI]) VALUES (5, N'D.ANADOLU')
	INSERT [dbo].[TBL_BOLGE] ([ID], [BOLGEADI]) VALUES (6, N'KARADENİZ')
	INSERT [dbo].[TBL_BOLGE] ([ID], [BOLGEADI]) VALUES (7, N'İÇ ANADOLU')
	SET IDENTITY_INSERT [dbo].[TBL_BOLGE] OFF
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_IL]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_IL](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BOLGEID] [int] NOT NULL,
		[ILADI] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_TBL_IL] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[TBL_IL]  WITH CHECK ADD  CONSTRAINT [FK_TBL_IL_TBL_BOLGE] FOREIGN KEY([BOLGEID])
	REFERENCES [dbo].[TBL_BOLGE] ([ID])
	
	ALTER TABLE [dbo].[TBL_IL] CHECK CONSTRAINT [FK_TBL_IL_TBL_BOLGE]

	SET IDENTITY_INSERT [dbo].[TBL_IL] ON 
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (1, 3, N'Adana')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (2, 4, N'Adıyaman')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (3, 2, N'Afyonkarahisar')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (4, 5, N'Ağrı')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (5, 6, N'Amasya')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (6, 7, N'Ankara')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (7, 3, N'Antalya')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (8, 6, N'Artvin')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (9, 2, N'Aydın')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (10, 1, N'Balıkesir')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (11, 1, N'Bilecik')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (12, 5, N'Bingöl')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (13, 5, N'Bitlis')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (14, 6, N'Bolu')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (15, 3, N'Burdur')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (16, 1, N'Bursa')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (17, 1, N'Çanakkale')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (18, 7, N'Çankırı')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (19, 6, N'Çorum')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (20, 2, N'Denizli')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (21, 4, N'Diyarbakır')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (22, 1, N'Edirne')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (23, 5, N'Elazığ')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (24, 5, N'Erzincan')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (25, 5, N'Erzurum')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (26, 7, N'Eskişehir')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (27, 4, N'Gaziantep')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (28, 6, N'Giresun')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (29, 6, N'Gümüşhane')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (30, 5, N'Hakkari')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (31, 3, N'Hatay')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (32, 3, N'Isparta')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (33, 3, N'Mersin')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (34, 1, N'İstanbul')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (35, 2, N'İzmir')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (36, 5, N'Kars')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (37, 6, N'Kastamonu')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (38, 7, N'Kayseri')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (39, 1, N'Kirklareli')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (40, 7, N'Kırşehir')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (41, 1, N'Kocaeli')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (42, 3, N'Kahramanmaraş')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (43, 7, N'Konya')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (44, 2, N'Kütahya')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (45, 5, N'Malatya')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (46, 2, N'Manisa')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (47, 4, N'Mardin')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (48, 2, N'Muğla')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (49, 5, N'Muş')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (50, 7, N'Nevşehir')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (51, 7, N'Niğde')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (52, 6, N'Ordu')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (53, 6, N'Rize')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (54, 1, N'Sakarya')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (55, 6, N'Samsun')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (56, 4, N'Siirt')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (57, 6, N'Sinop')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (58, 7, N'Sivas')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (59, 1, N'Tekirdağ')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (60, 6, N'Tokat')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (61, 6, N'Trabzon')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (62, 5, N'Tunceli')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (63, 4, N'Şanlıurfa')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (64, 2, N'Uşak')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (65, 5, N'Van')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (66, 7, N'Yozgat')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (67, 6, N'Zonguldak')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (68, 7, N'Aksaray')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (69, 6, N'Bayburt')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (70, 7, N'Karaman')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (71, 7, N'Kırıkkale')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (72, 4, N'Batman')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (73, 4, N'Şırnak')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (74, 6, N'Bartın')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (75, 5, N'Ardahan')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (76, 5, N'Iğdır')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (77, 1, N'Yalova')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (78, 6, N'Karabük')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (79, 4, N'Kilis')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (80, 3, N'Osmaniye')
	INSERT [dbo].[TBL_IL] ([ID], [BOLGEID], [ILADI]) VALUES (81, 6, N'Düzce')
	SET IDENTITY_INSERT [dbo].[TBL_IL] OFF
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_ILCE]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_ILCE](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ILID] [int] NOT NULL,
		[ILCEADI] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_TBL_ILCE] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[TBL_ILCE]  WITH CHECK ADD  CONSTRAINT [FK_TBL_ILCE_TBL_IL] FOREIGN KEY([ILID])
	REFERENCES [dbo].[TBL_IL] ([ID])

	ALTER TABLE [dbo].[TBL_ILCE] CHECK CONSTRAINT [FK_TBL_ILCE_TBL_IL]

	SET IDENTITY_INSERT [dbo].[TBL_ILCE] ON 
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 1,1,'Çukurova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 2,1,'Girne'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 3,2,'Gölbaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 4,2,'Tut'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 5,3,'Bayat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 6,3,'Çobanlar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 7,3,'Şuhut'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 8,4,'Eleşkirt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 9,4,'Hamur'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 10,4,'Patnos'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 11,5,'Gümüşhacıköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 12,5,'Merzifon'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 13,6,'Evren'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 14,6,'Güdül'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 15,6,'Kazan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 16,6,'Pursaklar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 17,7,'Aksu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 18,7,'Demre(Kale)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 19,7,'Gazipaşa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 20,7,'Kaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 21,7,'Konyaaltı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 22,7,'Muratpaşa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 23,8,'Arhavi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 24,8,'Borçka'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 25,8,'Hopa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 26,9,'Buharkent(Çubukdağı)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 27,9,'Çine'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 28,9,'İncirliova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 29,9,'Karacasu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 30,9,'Karpuzlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 31,9,'Köşk'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 32,9,'Nazilli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 33,9,'Sultanhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 34,10,'Ayvalık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 35,10,'Balya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 36,10,'Burhaniye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 37,10,'Edremit'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 38,10,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 39,10,'Sındırgı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 40,11,'Gölpazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 41,11,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 42,12,'Adaklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 43,12,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 44,12,'Yedisu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 45,13,'Adilcevaz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 46,13,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 47,14,'Dörtdivan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 48,14,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 49,15,'Altınyayla(Dirmil)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 50,16,'Büyükorhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 51,16,'Gemlik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 52,16,'Mustafakemalpaşa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 53,16,'Nilüfer'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 54,17,'Bayramiç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 55,17,'Eceabat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 56,17,'Yenice'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 57,18,'Atkaracalar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 58,18,'Bayramören'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 59,18,'Çerkeş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 60,18,'Yapraklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 61,19,'Bayat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 62,19,'İskilip'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 63,19,'Osmancık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 64,19,'Uğurludağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 65,20,'Baklan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 66,20,'Çal'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 67,20,'Güney'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 68,20,'Tavas'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 69,21,'Çınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 70,21,'Çüngüş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 71,21,'Dicle'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 72,21,'Lice'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 73,21,'Sur'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 74,21,'Yenişehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 75,22,'Keşan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 76,22,'Süloğlu(Süleoğlu)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 77,23,'Alacakaya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 78,23,'Kovancılar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 79,24,'Kemaliye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 80,25,'Karaçoban'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 81,25,'Narman'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 82,25,'Oltu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 83,25,'Olur'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 84,25,'Tekman'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 85,25,'Tortum'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 86,25,'Uzundere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 87,26,'Çifteler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 88,26,'Han'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 89,26,'Mihalgazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 90,26,'Mihalıççık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 91,26,'Tepebaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 92,27,'İslahiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 93,27,'Yavuzeli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 94,28,'Alucra'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 95,28,'Bulancak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 96,28,'Çanakçı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 97,28,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 98,28,'Yağlıdere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 99,29,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 100,29,'Torul'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 101,30,'Çukurca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 102,30,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 103,32,'Atabey'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 104,32,'Sütçüler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 105,32,'Uluborlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 106,33,'Akdeniz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 107,33,'Aydıncık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 108,33,'Bozyazı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 109,34,'Adalar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 110,34,'Avcılar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 111,34,'Beykoz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 112,34,'Çatalca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 113,34,'Esenler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 114,34,'Eyüp'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 115,34,'Fatih'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 116,34,'Gaziosmanpaşa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 117,34,'Kağıthane'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 118,34,'Kartal'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 119,34,'Pendik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 120,34,'Sarıyer'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 121,34,'Sultangazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 122,34,'Tuzla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 123,34,'Zeytinburnu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 124,35,'Balçova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 125,35,'Bayındır'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 126,35,'Çiğli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 127,35,'Güzelbahçe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 128,35,'Karabağlar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 129,35,'Karaburun'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 130,35,'Kemalpaşa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 131,35,'Konak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 132,35,'Ödemiş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 133,35,'Tire'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 134,36,'Arpaçay'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 135,37,'Azdavay'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 136,37,'Hanönü(Gökçeağaç)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 137,37,'İnebolu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 138,38,'Hacılar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 139,39,'Demirköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 140,39,'Kofçaz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 141,39,'Pehlivanköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 142,39,'Vize'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 143,40,'Akpınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 144,40,'Boztepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 145,41,'Dilovası'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 146,41,'Körfez(Tütünçiftlik)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 147,42,'Çağlıyancerit'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 148,42,'Nurhak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 149,43,'Akören'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 150,43,'Çumra'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 151,43,'Derbent'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 152,43,'Doğanhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 153,43,'Emirgazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 154,43,'Ereğli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 155,43,'Ilgın'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 156,43,'Sarayönü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 157,44,'Çavdarhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 158,44,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 159,44,'Tavşanlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 160,45,'Akçadağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 161,45,'Doğanşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 162,45,'Kuluncak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 163,45,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 164,46,'Gölmarmara'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 165,46,'Gördes'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 166,46,'Kula'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 167,46,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 168,46,'Sarıgöl'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 169,46,'Selendi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 170,46,'Soma'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 171,47,'Dargeçit'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 172,47,'Derik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 173,47,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 174,48,'Köyceğiz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 175,48,'Milas'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 176,49,'Hasköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 177,49,'Malazgirt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 178,50,'Avanos'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 179,50,'Kozaklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 180,51,'Çamardı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 181,51,'Ulukışla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 182,52,'Akkuş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 183,52,'Çatalpınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 184,52,'Çaybaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 185,52,'Gülyalı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 186,53,'Derepazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 187,54,'Arifiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 188,54,'Hendek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 189,54,'Karasu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 190,54,'Kaynarca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 191,54,'Sapanca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 192,54,'Serdivan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 193,55,'Canik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 194,55,'Çarşamba'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 195,55,'Terme'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 196,55,'Vezirköprü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 197,56,'Aydınlar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 198,56,'Baykan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 199,57,'Ayancık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 200,57,'Boyabat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 201,57,'Durağan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 202,58,'Gürün'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 203,58,'Kangal'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 204,58,'Koyulhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 205,59,'Çorlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 206,60,'Almus'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 207,60,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 208,60,'Pazar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 209,60,'Reşadiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 210,61,'Beşikdüzü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 211,61,'Düzköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 212,61,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 213,61,'Tonya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 214,62,'Hozat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 215,62,'Mazgirt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 216,62,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 217,62,'Pülümür'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 218,63,'Halfeti'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 219,63,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 220,63,'Siverek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 221,64,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 222,65,'Çatak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 223,65,'Edremit(Gümüşdere)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 224,65,'Erciş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 225,65,'Gevaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 226,65,'Gürpınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 227,65,'Saray'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 228,66,'Akdağmadeni'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 229,1,'Karaisalı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 230,1,'Karataş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 231,1,'Seyhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 232,1,'Yumurtalık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 233,2,'Besni'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 234,2,'Çelikhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 235,2,'Gerger'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 236,2,'Samsat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 237,3,'Başmakçı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 238,3,'Bolvadin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 239,3,'Dazkırı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 240,3,'Emirdağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 241,3,'Evciler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 242,3,'İscehisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 243,3,'Kızılören'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 244,3,'Sandıklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 245,4,'Diyadin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 246,4,'Tutak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 247,5,'Hamamözü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 248,6,'Çubuk'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 249,6,'Etimesgut'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 250,6,'Gölbaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 251,6,'Haymana'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 252,6,'Mamak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 253,6,'Polatlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 254,7,'Döşemealtı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 255,7,'Finike'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 256,7,'Manavgat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 257,9,'Kuşadası'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 258,9,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 259,9,'Söke'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 260,9,'Yenipazar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 261,10,'Havran'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 262,10,'Kepsut'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 263,10,'Marmara'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 264,10,'Savaştepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 265,12,'Genç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 266,13,'Güroymak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 267,14,'Göynük'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 268,14,'Kıbrıscık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 269,14,'Mengen'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 270,15,'Çavdır'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 271,15,'Kemer'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 272,16,'İnegöl'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 273,16,'Keles'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 274,16,'Mudanya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 275,16,'Orhaneli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 276,16,'Orhangazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 277,16,'Yenişehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 278,16,'Yıldırım'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 279,17,'Ayvacık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 280,17,'Bozcaada'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 281,17,'Ezine'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 282,17,'Gelibolu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 283,17,'Lapseki'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 284,18,'Eldivan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 285,18,'Ilgaz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 286,18,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 287,19,'Dodurga'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 288,19,'Kargı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 289,19,'Mecitözü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 290,20,'Babadağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 291,20,'Buldan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 292,20,'Sarayköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 293,20,'Serinhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 294,21,'Bismil'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 295,21,'Silvan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 296,22,'Havsa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 297,23,'Baskil'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 298,23,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 299,23,'Palu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 300,23,'Sivrice'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 301,24,'Üzümlü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 302,25,'Horasan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 303,25,'İspir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 304,25,'Pasinler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 305,25,'Şenkaya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 306,26,'Alpu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 307,26,'Günyüzü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 308,26,'Sarıcakaya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 309,27,'Karkamış'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 310,27,'Nizip'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 311,27,'Oğuzeli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 312,27,'Şahinbey'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 313,28,'Dereli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 314,28,'Eynesil'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 315,28,'Güce'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 316,28,'Keşap'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 317,29,'Köse'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 318,29,'Kürtün'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 319,31,'İskenderun'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 320,31,'Kumlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 321,32,'Gönen'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 322,32,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 323,33,'Çamlıyayla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 324,33,'Erdemli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 325,33,'Mut'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 326,33,'Toroslar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 327,34,'Arnavutköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 328,34,'Bağcılar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 329,34,'Bayrampaşa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 330,34,'Esenyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 331,34,'Maltepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 332,34,'Silivri'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 333,34,'Şişli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 334,34,'Üsküdar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 335,35,'Bayraklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 336,35,'Dikili'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 337,35,'Seferihisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 338,36,'Kağızman'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 339,36,'Susuz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 340,37,'Araç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 341,37,'Bozkurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 342,37,'Cide'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 343,37,'Çatalzeytin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 344,37,'Daday'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 345,37,'Devrekani'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 346,37,'Doğanyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 347,37,'İhsangazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 348,37,'Küre'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 349,37,'Seydiler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 350,37,'Taşköprü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 351,38,'Akkışla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 352,38,'Bünyan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 353,38,'Tomarza'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 354,38,'Yahyalı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 355,39,'Lüleburgaz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 356,40,'Kaman'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 357,41,'Darıca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 358,41,'Derince'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 359,41,'Gebze'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 360,41,'Karamürsel'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 361,42,'Andırın'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 362,42,'Ekinözü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 363,43,'Bozkır'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 364,43,'Güneysınır'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 365,43,'Hadim'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 366,43,'Hüyük'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 367,43,'Seydişehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 368,43,'Yunak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 369,44,'Domaniç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 370,45,'Arapkir(Arapgir)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 371,45,'Battalgazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 372,45,'Hekimhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 373,45,'Yeşilyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 374,46,'Ahmetli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 375,46,'Demirci'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 376,46,'Salihli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 377,47,'Mazıdağı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 378,48,'Dalaman'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 379,48,'Datça'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 380,48,'Kavaklıdere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 381,48,'Marmaris'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 382,48,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 383,48,'Ortaca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 384,49,'Bulanık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 385,49,'Varto'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 386,50,'Derinkuyu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 387,50,'Gülşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 388,50,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 389,51,'Çiftlik(Özyurt)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 390,52,'Aybastı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 391,52,'Fatsa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 392,52,'İkizce'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 393,52,'Kumru'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 394,52,'Ulubey'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 395,53,'Çamlıhemşin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 396,54,'Akyazı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 397,54,'Geyve'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 398,54,'Pamukova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 399,55,'Asarcık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 400,55,'Havza'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 401,55,'İlkadım'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 402,55,'Ondokuzmayıs(Ballıca)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 403,55,'Salıpazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 404,57,'Dikmen'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 405,57,'Erfelek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 406,57,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 407,57,'Saraydüzü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 408,58,'Gemerek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 409,58,'Gölova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 410,58,'Hafik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 411,58,'Suşehri'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 412,58,'Şarkışla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 413,58,'Yıldızeli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 414,59,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 415,59,'Şarköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 416,60,'Artova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 417,60,'Erbaa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 418,60,'Niksar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 419,60,'Sulusaray'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 420,61,'Çarşıbaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 421,61,'Çaykara'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 422,61,'Sürmene'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 423,61,'Vakfıkebir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 424,62,'Çemişgezek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 425,62,'Ovacık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 426,65,'Muradiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 427,66,'Kadışehri'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 428,66,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 429,66,'Şefaatli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 430,66,'Yenifakılı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 431,67,'Gökçebey'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 432,68,'Ağaçören'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 433,68,'Gülağaç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 434,68,'Güzelyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 435,68,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 436,68,'Ortaköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 437,70,'Ayrancı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 438,70,'Başyayla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 439,70,'Ermenek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 440,71,'Delice'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 441,71,'Keskin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 442,72,'Beşiri'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 443,73,'Cizre'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 444,73,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 445,74,'Amasra'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 446,74,'Kurucaşile'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 447,75,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 448,77,'Armutlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 449,78,'Ovacık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 450,78,'Yenice'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 451,81,'Akçakoca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 452,81,'Kaynaşlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 453,81,'Yığılca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 454,1,'Aladağ(Karsantı)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 455,1,'Ceyhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 456,1,'Feke'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 457,1,'İmamoğlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 458,1,'Kozan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 459,1,'Tufanbeyli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 460,2,'Kahta'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 461,2,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 462,2,'Sincik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 463,3,'Çay'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 464,3,'Dinar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 465,3,'Hocalar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 466,3,'İhsaniye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 467,3,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 468,3,'Sultandağı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 469,4,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 470,4,'Taşlıçay'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 471,5,'Göynücek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 472,5,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 473,5,'Suluova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 474,5,'Taşova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 475,6,'Akyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 476,6,'Ayaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 477,6,'Çankaya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 478,6,'Elmadağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 479,6,'Nallıhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 480,6,'Sincan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 481,7,'Akseki'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 482,7,'Alanya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 483,7,'İbradı(Aydınkent)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 484,7,'Kepez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 485,7,'Korkuteli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 486,7,'Kumluca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 487,7,'Serik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 488,8,'Murgul(Göktaş)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 489,8,'Yusufeli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 490,9,'Bozdoğan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 491,9,'Germencik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 492,9,'Kuyucak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 493,10,'Bandırma'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 494,10,'Bigadiç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 495,10,'Gömeç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 496,11,'Bozüyük'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 497,11,'İnhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 498,11,'Pazaryeri'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 499,11,'Söğüt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 500,11,'Yenipazar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 501,12,'Yayladere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 502,13,'Hizan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 503,13,'Mutki'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 504,14,'Mudurnu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 505,15,'Ağlasun'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 506,15,'Bucak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 507,15,'Çeltikçi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 508,15,'Yeşilova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 509,16,'İznik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 510,16,'Karacabey'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 511,16,'Osmangazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 512,17,'Biga'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 513,18,'Kızılırmak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 514,18,'Şabanözü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 515,19,'Alaca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 516,19,'Laçin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 517,19,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 518,19,'Oğuzlar(Karaören)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 519,19,'Sungurlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 520,20,'Acıpayam'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 521,20,'Beyağaç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 522,20,'Çardak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 523,20,'Honaz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 524,20,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 525,21,'Çermik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 526,21,'Eğil'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 527,21,'Ergani'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 528,21,'Hazro'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 529,21,'Kayapınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 530,21,'Kulp'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 531,22,'İpsala'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 532,22,'Meriç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 533,22,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 534,22,'Uzunköprü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 535,24,'Çayırlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 536,24,'Kemah'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 537,24,'Tercan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 538,25,'Aşkale'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 539,25,'Aziziye(Ilıca)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 540,25,'Çat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 541,25,'Karayazı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 542,25,'Köprüköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 543,25,'Palandöken'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 544,25,'Yakutiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 545,26,'Beylikova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 546,26,'İnönü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 547,26,'Mahmudiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 548,27,'Nurdağı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 549,28,'Doğankent'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 550,28,'Görele'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 551,30,'Yüksekova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 552,31,'Dörtyol'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 553,31,'Hassa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 554,31,'Reyhanlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 555,31,'Samandağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 556,31,'Yayladağı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 557,32,'Aksu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 558,32,'Eğirdir(Eğridir)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 559,32,'Gelendost'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 560,32,'Keçiborlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 561,32,'Senirkent'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 562,32,'Şarkikaraağaç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 563,32,'Yalvaç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 564,33,'Anamur'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 565,33,'Gülnar (Gülpınar)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 566,33,'Silifke'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 567,34,'Bakırköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 568,34,'Başakşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 569,34,'Beşiktaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 570,34,'Beylikdüzü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 571,34,'Büyükçekmece'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 572,34,'Kadıköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 573,34,'Sancaktepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 574,34,'Sultanbeyli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 575,35,'Aliağa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 576,35,'Beydağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 577,35,'Buca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 578,35,'Çeşme'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 579,35,'Foça'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 580,35,'Gaziemir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 581,35,'Kınık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 582,35,'Kiraz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 583,35,'Torbalı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 584,35,'Urla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 585,36,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 586,37,'Abana'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 587,37,'Ağlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 588,37,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 589,37,'Pınarbaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 590,37,'Tosya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 591,38,'Felahiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 592,38,'İncesu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 593,38,'Kocasinan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 594,38,'Pınarbaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 595,38,'Sarız'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 596,38,'Talas'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 597,39,'Babaeski'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 598,39,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 599,40,'Mucur'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 600,42,'Afşin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 601,42,'Elbistan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 602,42,'Pazarcık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 603,43,'Akşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 604,43,'Altınekin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 605,43,'Cihanbeyli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 606,43,'Çeltik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 607,43,'Derebucak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 608,43,'Kadınhanı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 609,43,'Karapınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 610,43,'Kulu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 611,43,'Selçuklu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 612,43,'Yalıhüyük'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 613,44,'Dumlupınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 614,44,'Emet'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 615,44,'Gediz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 616,44,'Hisarcık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 617,44,'Pazarlar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 618,44,'Şaphane'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 619,45,'Darende'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 620,45,'Pütürge(Pötürge)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 621,45,'Yazıhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 622,46,'Köprübaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 623,46,'Saruhanlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 624,47,'Kızıltepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 625,48,'Bodrum'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 626,50,'Acıgöl'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 627,51,'Altunhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 628,52,'Gölköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 629,52,'Gürgentepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 630,52,'Kabadüz(Karadüz)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 631,52,'Korgan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 632,52,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 633,52,'Mesudiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 634,52,'Ünye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 635,53,'Ardeşen'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 636,53,'Çayeli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 637,53,'Fındıklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 638,53,'Hemşin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 639,53,'İyidere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 640,53,'Kalkandere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 641,53,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 642,54,'Karapürçek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 643,54,'Söğütlü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 644,55,'Ayvacık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 645,55,'Kavak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 646,55,'Ladik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 647,55,'Tekkeköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 648,55,'Yakakent'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 649,56,'Pervari'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 650,56,'Şirvan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 651,57,'Türkeli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 652,58,'Akıncılar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 653,58,'Altınyayla'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 654,58,'Divriği'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 655,58,'Doğanşar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 656,58,'İmranlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 657,58,'Ulaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 658,59,'Çerkezköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 659,59,'Marmaraereğlisi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 660,60,'Zile'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 661,61,'Akçaabat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 662,61,'Arsin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 663,61,'Dernekpazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 664,61,'Köprübaşı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 665,61,'Maçka'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 666,61,'Of'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 667,61,'Şalpazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 668,61,'Yomra'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 669,63,'Akçakale'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 670,63,'Bozova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 671,63,'Ceylanpınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 672,63,'Harran'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 673,63,'Suruç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 674,64,'Eşme'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 675,64,'Karahallı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 676,64,'Ulubey'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 677,65,'Başkale'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 678,65,'Çaldıran'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 679,65,'Özalp'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 680,66,'Boğazlıyan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 681,66,'Aydıncık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 682,66,'Sorgun'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 683,67,'Devrek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 684,67,'Karadenizereğli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 685,70,'Sarıveliler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 686,71,'Balışeyh'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 687,71,'Yahşihan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 688,72,'Kozluk'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 689,73,'Beytüşşebap'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 690,73,'İdil'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 691,75,'Çıldır'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 692,76,'Aralık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 693,76,'Tuzluca'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 694,77,'Çınarcık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 695,77,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 696,78,'Eflani'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 697,78,'Eskipazar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 698,78,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 699,78,'Safranbolu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 700,79,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 701,80,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 702,80,'Toprakkale'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 703,81,'Cumayeri'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 704,66,'Çandır'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 705,66,'Çayıralan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 706,66,'Çekerek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 707,67,'Çaycuma'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 708,68,'Eskil'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 709,69,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 710,70,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 711,71,'Bahşili'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 712,71,'Çelebi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 713,71,'Karakeçili'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 714,71,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 715,72,'Gercüş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 716,72,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 717,73,'Uludere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 718,74,'Ulus'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 719,75,'Damal'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 720,75,'Hanak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 721,75,'Posof'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 722,76,'Karakoyunlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 723,77,'Altınova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 724,77,'Çiftlikköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 725,80,'Kadirli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 726,81,'Gölyaka'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 727,1,'Gazimagosa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 728,1,'Güzelyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 729,1,'Pozantı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 730,1,'Saimbeyli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 731,1,'Sarıçam'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 732,1,'Yüreğir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 733,3,'Sincanlı(Sinanpaşa)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 734,4,'Doğubayazıt(Doğubeyazıt)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 735,6,'Altındağ'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 736,6,'Bala'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 737,6,'Beypazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 738,6,'Çamlıdere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 739,6,'Kalecik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 740,6,'Keçiören'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 741,6,'Kızılcahamam'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 742,6,'Şereflikoçhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 743,6,'Yenimahalle'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 744,7,'Elmalı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 745,7,'Gündoğmuş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 746,7,'Kemer'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 747,8,'Ardanuç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 748,8,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 749,8,'Şavşat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 750,9,'Didim(Yenihisar)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 751,9,'Koçarlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 752,10,'Dursunbey'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 753,10,'Erdek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 754,10,'Gönen'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 755,10,'İvrindi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 756,10,'Manyas'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 757,10,'Susurluk'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 758,11,'Osmaneli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 759,12,'Karlıova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 760,12,'Kiğı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 761,12,'Solhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 762,13,'Ahlat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 763,13,'Tatvan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 764,14,'Gerede'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 765,14,'Seben'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 766,14,'Yeniçağa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 767,15,'Gölhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 768,15,'Karamanlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 769,15,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 770,15,'Tefenni'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 771,16,'Gürsu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 772,16,'Harmancık'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 773,16,'Kestel'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 774,17,'Çan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 775,17,'Gökçeada(İmroz)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 776,17,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 777,18,'Korgun'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 778,18,'Kurşunlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 779,18,'Orta'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 780,19,'Boğazkale'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 781,19,'Ortaköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 782,20,'Akköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 783,20,'Bekilli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 784,20,'Bozkurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 785,20,'Çameli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 786,20,'Çivril'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 787,20,'Kale'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 788,21,'Bağlar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 789,21,'Hani'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 790,21,'Kocaköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 791,22,'Enez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 792,22,'Lalapaşa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 793,23,'Ağın'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 794,23,'Arıcak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 795,23,'Karakoçan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 796,23,'Keban'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 797,23,'Maden'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 798,24,'Ilıç(İliç)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 799,24,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 800,24,'Otlukbeli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 801,24,'Refahiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 802,25,'Hınıs'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 803,25,'Pazaryolu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 804,26,'Odunpazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 805,26,'Seyitgazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 806,26,'Sivrihisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 807,27,'Araban'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 808,27,'Şehitkamil'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 809,28,'Çamoluk'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 810,28,'Espiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 811,28,'Piraziz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 812,28,'Şebinkarahisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 813,28,'Tirebolu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 814,29,'Kelkit'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 815,29,'Şiran'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 816,30,'Şemdinli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 817,31,'Altınözü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 818,31,'Antakya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 819,31,'Belen'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 820,31,'Erzin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 821,31,'Kırıkhan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 822,32,'Yenişarbademli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 823,33,'Mezitli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 824,33,'Tarsus'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 825,33,'Yenişehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 826,34,'Ataşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 827,34,'Bahçelievler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 828,34,'Beyoğlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 829,34,'Çekmeköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 830,34,'Güngören'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 831,34,'Küçükçekmece'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 832,34,'Şile'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 833,34,'Ümraniye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 834,35,'Bergama'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 835,35,'Bornova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 836,35,'Karşıyaka'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 837,35,'Menderes(Cumaovası)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 838,35,'Menemen'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 839,35,'Narlıdere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 840,35,'Selçuk'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 841,36,'Akyaka'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 842,36,'Digor'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 843,36,'Sarıkamış'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 844,36,'Selim'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 845,37,'Şenpazar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 846,38,'Develi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 847,38,'Melikgazi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 848,38,'Özvatan(Çukur)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 849,38,'Sarıoğlan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 850,38,'Yeşilhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 851,39,'Pınarhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 852,40,'Akçakent'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 853,40,'Çiçekdağı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 854,40,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 855,41,'Başiskele'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 856,41,'Çayırova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 857,41,'Gölcük'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 858,41,'İzmit'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 859,41,'Kandıra'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 860,41,'Kartepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 861,42,'Göksun'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 862,42,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 863,42,'Türkoğlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 864,43,'Ahırlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 865,43,'Beyşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 866,43,'Halkapınar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 867,43,'Karatay'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 868,43,'Meram'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 869,43,'Taşkent'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 870,43,'Tuzlukçu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 871,44,'Altıntaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 872,44,'Aslanapa'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 873,44,'Simav'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 874,45,'Arguvan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 875,45,'Doğanyol'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 876,45,'Kale'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 877,46,'Akhisar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 878,46,'Alaşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 879,46,'Kırkağaç'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 880,46,'Turgutlu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 881,47,'Midyat(Estel)'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 882,47,'Nusaybin'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 883,47,'Ömerli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 884,47,'Savur'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 885,47,'Yeşilli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 886,48,'Fethiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 887,48,'Ula'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 888,48,'Yatağan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 889,49,'Korkut'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 890,49,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 891,50,'Hacıbektaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 892,50,'Ürgüp'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 893,51,'Bor'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 894,51,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 895,52,'Çamaş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 896,52,'Kabataş'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 897,52,'Perşembe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 898,53,'Güneysu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 899,53,'İkizdere'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 900,53,'Pazar'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 901,54,'Adapazarı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 902,54,'Erenler'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 903,54,'Ferizli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 904,54,'Kocaali'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 905,54,'Taraklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 906,55,'Alaçam'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 907,55,'Atakum'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 908,55,'Bafra'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 909,56,'Eruh'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 910,56,'Kurtalan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 911,56,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 912,57,'Gerze'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 913,58,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 914,58,'Zara'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 915,59,'Hayrabolu'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 916,59,'Malkara'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 917,59,'Muratlı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 918,59,'Saray'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 919,60,'Başçiftlik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 920,60,'Turhal'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 921,60,'Yeşilyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 922,61,'Araklı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 923,61,'Hayrat'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 924,62,'Nazımiye'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 925,62,'Pertek'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 926,63,'Birecik'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 927,63,'Hilvan'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 928,63,'Viranşehir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 929,64,'Banaz'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 930,64,'Sivaslı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 931,65,'Bahçesaray'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 932,65,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 933,66,'Saraykent'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 934,66,'Sarıkaya'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 935,66,'Yerköy'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 936,67,'Alaplı'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 937,67,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 938,68,'Sarıyahşi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 939,69,'Aydıntepe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 940,69,'Demirözü'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 941,70,'Kazımkarabekir'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 942,71,'Sulakyurt'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 943,72,'Hasankeyf'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 944,72,'Sason'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 945,73,'Güçlükonak'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 946,73,'Silopi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 947,74,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 948,75,'Göle'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 949,76,'Merkez'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 950,77,'Termal'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 951,79,'Elbeyli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 952,79,'Musabeyli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 953,79,'Polateli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 954,80,'Bahçe'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 955,80,'Düziçi'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 956,80,'Hasanbeyli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 957,80,'Sumbas'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 958,81,'Çilimli'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 959,81,'Gümüşova'
	INSERT INTO TBL_ILCE(ID, ILID, ILCEADI) SELECT 960,81,'Merkez'
	SET IDENTITY_INSERT [dbo].[TBL_ILCE] OFF

END
GO





IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_PROMOSYON') AND name='PLUNO')
ALTER TABLE dbo.TBL_FIS_PROMOSYON ADD
	PLUNO int NULL
GO


ALTER FUNCTION [dbo].[CHECKSUMKONTROL](@BARKOD	VARCHAR(20), @UZUNLUK TINYINT)
RETURNS VARCHAR(MAX)
AS
BEGIN
IF PATINDEX('%[^0-9]%', @BARKOD) > 0 RETURN @BARKOD
DECLARE
	@MAXBARKOD		BIGINT,
	@RETBARKOD		VARCHAR(20)

	SET @RETBARKOD = NULL

	IF @UZUNLUK NOT IN (7,8,13)   SET @RETBARKOD = @BARKOD

	IF LEN(@BARKOD) >= @UZUNLUK SET @RETBARKOD = @BARKOD

	IF @UZUNLUK = 7	SET @RETBARKOD = @BARKOD

	IF @RETBARKOD IS NULL
	BEGIN
		DECLARE @ICOUNTER 	INT,
				@TOPLAM		INT


		SET @TOPLAM = 0
		SET @RETBARKOD = REVERSE(@BARKOD)
		SET @ICOUNTER = 1

		WHILE @ICOUNTER <= LEN(@RETBARKOD)
		BEGIN

			IF  @ICOUNTER % 2 = 1
				SET @TOPLAM = @TOPLAM + CONVERT(INT, SUBSTRING(@RETBARKOD, @ICOUNTER, 1)) * 3
			ELSE
				SET @TOPLAM = @TOPLAM + (CONVERT(INT, SUBSTRING(@RETBARKOD, @ICOUNTER, 1)) )

			SET @ICOUNTER = @ICOUNTER + 1
		END

		SET @RETBARKOD = @BARKOD + CONVERT(VARCHAR(1), ((10 - (@TOPLAM % 10)) % 10))
	END

	RETURN @RETBARKOD 
END
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_FIS_SIPARIS_BILGILERI]') AND type in (N'U'))
CREATE TABLE [dbo].[TBL_FIS_SIPARIS_BILGILERI](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FISID] [int] NOT NULL,
	[SIPARISID] [int] NULL,
	[DELIVERYTIME] [datetime] NULL,
	[PLATFORMTYPE] [tinyint] NULL,
	[CUSTOMERNAME] [varchar](255) NULL,
	[CUSTOMERPHONE] [varchar](255) NULL,
	[ORDERTOTAL] [money] NULL,
	[ADDRESS] [varchar](max) NULL,
	[ADDRESSDESCRIPTION] [varchar](max) NULL,
	[ORDERNOTE] [varchar](max) NULL,
	[KURYEADI] [varchar](50) NULL,
 CONSTRAINT [PK_TBL_FIS_SIPARIS_BILGILERI] PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

IF  NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[TBL_FIS_SIPARIS_BILGILERI]') AND name = N'IX_TBL_FIS_SIPARIS_BILGILERI')
CREATE NONCLUSTERED INDEX [IX_TBL_FIS_SIPARIS_BILGILERI] ON [dbo].[TBL_FIS_SIPARIS_BILGILERI]
(
	[FISID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF  NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'[dbo].[TBL_FIS_SIPARIS_BILGILERI]') AND name = N'FK_TBL_FIS_SIPARIS_BILGILERI_TBL_FIS_MAIN')
ALTER TABLE [dbo].[TBL_FIS_SIPARIS_BILGILERI]  WITH CHECK ADD  CONSTRAINT [FK_TBL_FIS_SIPARIS_BILGILERI_TBL_FIS_MAIN] FOREIGN KEY([FISID])
REFERENCES [dbo].[TBL_FIS_MAIN] ([ID])
GO

ALTER TABLE [dbo].[TBL_FIS_SIPARIS_BILGILERI] CHECK CONSTRAINT [FK_TBL_FIS_SIPARIS_BILGILERI_TBL_FIS_MAIN]
GO

ALTER TRIGGER [dbo].[TRG_FIS_MAIN_INSTEADOF_DELETE]
ON  [dbo].[TBL_FIS_MAIN]
INSTEAD OF DELETE
AS
BEGIN
	SET NOCOUNT ON;

	DELETE FROM TBL_FIS_DETAY		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_ODEME		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_PROMOSYON	WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_LOG			WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_SLIP		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_SIPARIS_BILGILERI WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_MAIN		WHERE ID IN (SELECT ID FROM DELETED)
END
GO





IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_HEDIYE_CEK]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_HEDIYE_CEK](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[KASANO] [varchar](10) NOT NULL,
		[CEKNO] [varchar](20) NOT NULL,
		[CARIADI] [varchar](50) NOT NULL,
		[TUTAR] [float] NOT NULL,
		[TARIH] [datetime] NOT NULL,
		[KASIYERADI] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_TBL_HEDIYE_CEK] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO




IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_USER_MAIN') AND name='YUZDEINDIRIMLIMITI')
ALTER TABLE dbo.TBL_USER_MAIN ADD
	YUZDEINDIRIMLIMITI decimal(4, 2) NULL,
	TUTARINDIRIMLIMITI decimal(21, 6) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_TUTAR') AND name='PUANYUZDE')
ALTER TABLE dbo.TBL_PROMOSYON_TUTAR ADD
	PUANYUZDE float(53) NULL
GO



















IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_MAIN') AND name='OKCNO')
ALTER TABLE dbo.TBL_BEKLETME_MAIN ADD
	OKCNO varchar(20) NULL
GO

SET IDENTITY_INSERT [dbo].[TBL_YETKI_TANIM] ON

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'MKTAZL')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (27, N'MKTAZL', N'Miktar Azaltma İşlemi')

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'MKTART')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (28, N'MKTART', N'Miktar Arttırma İşlemi')

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'CKMCAC')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (29, N'CKMCAC', N'Çekmece Aç')

SET IDENTITY_INSERT [dbo].[TBL_YETKI_TANIM] OFF
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='TEVKIFATKODU')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	TEVKIFATKODU varchar(10) NULL,
	TEVKIFATACIKLAMA varchar(100) NULL,
	TEVKIFATORANI int NULL,
	OTVKODU varchar(10) NULL,
	OTVACIKLAMA varchar(100) NULL,
	OTVORANI int NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_DETAY') AND name='TEVKIFATKODU')
ALTER TABLE dbo.TBL_BEKLETME_DETAY ADD
	TEVKIFATKODU varchar(10) NULL,
	TEVKIFATACIKLAMA varchar(100) NULL,
	TEVKIFATORANI int NULL,
	OTVKODU varchar(10) NULL,
	OTVACIKLAMA varchar(100) NULL,
	OTVORANI int NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_DETAY') AND name='TEVKIFATKODU')
ALTER TABLE dbo.TBL_FIS_DETAY ADD
	TEVKIFATKODU varchar(10) NULL,
	TEVKIFATACIKLAMA varchar(100) NULL,
	TEVKIFATORANI int NULL,
	OTVKODU varchar(10) NULL,
	OTVACIKLAMA varchar(100) NULL,
	OTVORANI int NULL
GO


IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='ALISFIYAT')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	ALISFIYAT float(53) NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_REYON') AND name='CARIGRUP')
ALTER TABLE dbo.TBL_PROMOSYON_REYON ADD
	CARIGRUP  varchar(MAX) NULL
GO




IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_CARI_EFATURA_TEMP]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_CARI_EFATURA_TEMP](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[ALIAS] [varchar](200) NOT NULL,
		[CREATEDATE] [datetime] NOT NULL,
		[IDENTIFIER] [varchar](20) NOT NULL,
		[AKTIF] [bit] NOT NULL,
		[TITLE] [varchar](max) NOT NULL,
		[TYPE] [varchar](20) NOT NULL,
		[UPDATEDATE] [datetime] NOT NULL,
	 CONSTRAINT [PK_TBL_CARI_EFATURA_TEMP] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
GO



ALTER FUNCTION [dbo].[CHECKEMAILFORMAT](@EMAIL VARCHAR(255))   
RETURNS BIT  
AS  
BEGIN  
     DECLARE @VALID BIT  
     IF @EMAIL IS NOT NULL   
          SET @EMAIL = LOWER(@EMAIL)  
          SET @VALID = 0  
          IF @EMAIL LIKE '[a-z,0-9,''_'',-+]%@[a-z,0-9,_,-]%.[a-z][a-z]%'  
             AND LEN(REPLACE(REPLACE(@EMAIL,'-',''),'+','')) = LEN(DBO.APPSTRIPNONEMAIL(@EMAIL))  
             AND @EMAIL NOT LIKE '%@%@%'  
             AND CHARINDEX('.@',@EMAIL) = 0  
             AND CHARINDEX('..',@EMAIL) = 0  
             AND CHARINDEX(',',@EMAIL) = 0  
             AND RIGHT(@EMAIL,1) BETWEEN 'a' AND 'z'  
               SET @VALID=1  
     RETURN @VALID  
END  
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_DEPARTMAN') AND name='DEPARTMANADI')
ALTER TABLE dbo.TBL_DEPARTMAN ADD
	DEPARTMANADI varchar(50) NULL
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_PROMOSYON_LIMIT]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_PROMOSYON_LIMIT](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BASLANGICTARIHI] [datetime] NOT NULL,
		[BITISTARIHI] [datetime] NOT NULL,
		[CARITIPI] [varchar](1) NOT NULL,
		[PLUNO] [int] NOT NULL,
		[LIMIT] [float] NOT NULL,
		[FIYATTIPI] [tinyint] NOT NULL,
	 CONSTRAINT [PK_TBL_PROMOSYON_LIMIT] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO




IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_YETKI_TIP') AND name='MOBIL')
ALTER TABLE dbo.TBL_YETKI_TIP ADD
	MOBIL bit NULL
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_STOK_OZEL_KOD]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_STOK_OZEL_KOD](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[BARKOD] [varchar](50) NOT NULL,
		[OZELKOD1] [varchar](50) NOT NULL,
		[OZELKOD2] [varchar](50) NOT NULL,
		[OZELKOD3] [varchar](50) NOT NULL,
		[OZELKOD4] [varchar](50) NOT NULL,
		[OZELKOD5] [varchar](50) NOT NULL,
		[OZELKOD6] [varchar](50) NOT NULL,
		[OZELKOD7] [varchar](50) NOT NULL,
		[OZELKOD8] [varchar](50) NOT NULL,
		[OZELKOD9] [varchar](50) NOT NULL,
		[OZELKOD10] [varchar](50) NOT NULL,
	 CONSTRAINT [PK_TBL_STOK_OZEL_KOD] PRIMARY KEY CLUSTERED 
	(
		[BARKOD] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO





UPDATE TBL_FIS_DETAY SET DOVIZTUTARI = TUTAR 
WHERE 
	TIP='IPT' AND DOVIZKODU = 'TL' AND 
	TUTAR<>DOVIZTUTARI
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_FIS_KDV]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_FIS_KDV](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[FISID] [int] NOT NULL,
		[KDV] [float] NOT NULL,
		[KDVTUTAR] [float] NOT NULL,
		[KDVHARICTUTAR] [float] NOT NULL,
		[TUTAR] [float] NOT NULL,
	 CONSTRAINT [PK_TBL_FIS_KDV] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
	CREATE NONCLUSTERED INDEX [IX_TBL_FIS_KDV] ON [dbo].[TBL_FIS_KDV]
	(
		[FISID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	ALTER TABLE [dbo].[TBL_FIS_KDV]  WITH CHECK ADD  CONSTRAINT [FK_TBL_FIS_KDV_TBL_FIS_MAIN] FOREIGN KEY([FISID])
	REFERENCES [dbo].[TBL_FIS_MAIN] ([ID])

	ALTER TABLE [dbo].[TBL_FIS_KDV] CHECK CONSTRAINT [FK_TBL_FIS_KDV_TBL_FIS_MAIN]
END
GO

ALTER TRIGGER [dbo].[TRG_FIS_MAIN_INSTEADOF_DELETE]
ON  [dbo].[TBL_FIS_MAIN]
INSTEAD OF DELETE
AS
BEGIN
	SET NOCOUNT ON;

	DELETE FROM TBL_FIS_DETAY		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_ODEME		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_PROMOSYON	WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_LOG			WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_SLIP		WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_KDV			WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_SIPARIS_BILGILERI WHERE FISID IN (SELECT ID FROM DELETED)
	DELETE FROM TBL_FIS_MAIN		WHERE ID IN (SELECT ID FROM DELETED)
END
GO



IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_MAIN') AND name='ISSEND')
ALTER TABLE dbo.TBL_FIS_MAIN ADD
	ISSEND bit NULL
GO


IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_CARI_MAIN') AND name='ISVERESIYE')
ALTER TABLE dbo.TBL_CARI_MAIN ADD
	ISVERESIYE bit NULL
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='ISINDIRIM')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	ISINDIRIM bit NULL
GO









SET IDENTITY_INSERT [dbo].[TBL_YETKI_TANIM] ON

IF NOT EXISTS(SELECT 1 FROM TBL_YETKI_TANIM WHERE YETKIKODU = 'MSTARA')
	INSERT [dbo].[TBL_YETKI_TANIM] ([ID], [YETKIKODU], [YETKIADI]) VALUES (30, N'MSTARA', N'Müşteri Arama')

SET IDENTITY_INSERT [dbo].[TBL_YETKI_TANIM] OFF
GO




IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_PROMOSYON_REYON') AND name='VREYONADI')
ALTER TABLE dbo.TBL_PROMOSYON_REYON ADD
	VREYONADI varchar(20) NULL
GO
























IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_DOVIZ_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_DOVIZ_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_DOVIZ_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_DOVIZ_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_ADET_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_ADET_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_BEKLETME_MAIN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_BEKLETME_MAIN]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_BEKLETME_LOG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_BEKLETME_LOG]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_BEKLETME_DETAY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_BEKLETME_DETAY]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BEKLETME_LOG_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BEKLETME_LOG_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BEKLETME_MAIN_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BEKLETME_MAIN_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_STOK_SATIS_ADET_REPORT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_STOK_SATIS_ADET_REPORT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_PROMOSYON]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_PROMOSYON]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_LOG_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_LOG_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_LOG]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_LOG]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_COUNT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_COUNT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_XZ_LOG_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_XZ_LOG_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_DETAY_LOG_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_DETAY_LOG_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_DEPARTMAN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_DEPARTMAN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_DEPARTMAN_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_DEPARTMAN_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_EFATURA_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_EFATURA_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_STATUS_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_STATUS_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_STATUS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_STATUS]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_SATIS_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_SATIS_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_SATIS_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_SATIS_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_SATIS_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_SATIS_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_SATIS_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_SATIS_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_REYON_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_REYON_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_XZ_LOG_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_XZ_LOG_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_ODEME_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_ODEME_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_XZ_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_XZ_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_TEK_FATURA_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_TEK_FATURA_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_KDV]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_KDV]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_SLIP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_SLIP]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_SLIP_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_SLIP_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_MAIN_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_MAIN_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_SIPARIS_STOK_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_SIPARIS_STOK_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_SATIS_REPORT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_SATIS_REPORT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_GET_DETAY_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_GET_DETAY_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_SIPARIS_PLATFORM_OPTION]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_SIPARIS_PLATFORM_OPTION]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_SIPARIS_PLATFORM_DETAY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_SIPARIS_PLATFORM_DETAY]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_DETAY_OPTION_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_DETAY_OPTION_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_OPTION_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_OPTION_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_OPTION_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_OPTION_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_DETAY_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_DETAY_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_MAIN_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_MAIN_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_SIPARIS_PLATFORM_MAIN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_SIPARIS_PLATFORM_MAIN]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_DETAY_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_DETAY_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_PAYMENT_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_PAYMENT_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_PLATFORM_PAYMENT_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_PAYMENT_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_TO_FIS_MAIN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_TO_FIS_MAIN]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_OUTPUT_MESSAGE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_OUTPUT_MESSAGE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_HAREKET_IBM_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_HAREKET_IBM_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_MAIN_BROWSE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_MAIN_BROWSE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_STOK_NOBONUS_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_STOK_NOBONUS_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MESAJ_CARI_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_MESAJ_CARI_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KURYE_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KURYE_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KURYE_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KURYE_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KURYE_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KURYE_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MESAJ_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_MESAJ_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_ADRES_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_ADRES_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MESAJ_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_MESAJ_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_DASHBOARD]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_DASHBOARD]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_ADRES_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_ADRES_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_ADRES_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_ADRES_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SUBE_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SUBE_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SUBE_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SUBE_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SUBE_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SUBE_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_STOK_SIPARIS_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_STOK_SIPARIS_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_SIPARIS_DETAY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_SIPARIS_DETAY]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_SIPARIS]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_SIPARIS]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_DETAY_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_DETAY_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_DETAY_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_DETAY_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SEPET_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SEPET_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SEPET_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SEPET_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SEPET_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SEPET_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_HAZIR_MESAJ_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_HAZIR_MESAJ_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_HAZIR_MESAJ_DELETE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_HAZIR_MESAJ_DELETE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_HAZIR_MESAJ_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_HAZIR_MESAJ_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_MESAJ_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_MESAJ_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_STOK_SATIS_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_STOK_SATIS_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_EFATURA_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_EFATURA_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SMS_KONTROL_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SMS_KONTROL_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SMS_KONTROL_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SMS_KONTROL_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CALLER_ID_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CALLER_ID_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CALLER_ID_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CALLER_ID_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_TALEP_MAIN_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_TALEP_MAIN_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_SIPARIS_TALEP_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_SIPARIS_TALEP_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KASA_TAKIP_FIS_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KASA_TAKIP_FIS_DETAY_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_DETAY_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KASA_TAKIP_FIS_DETAY_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_DETAY_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KASA_TAKIP_FIS_MAIN_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_MAIN_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_ODEME_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_ODEME_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_ODEME]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_ODEME]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BEKLETME_MAIN_BROWSE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BEKLETME_MAIN_BROWSE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_LOG_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_LOG_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BOLGE_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BOLGE_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IL_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IL_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_ILCE_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_ILCE_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_PROMOSYON_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_PROMOSYON_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_PROMOSYON_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_PROMOSYON_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_ODEME_KONTROL_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_ODEME_KONTROL_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_EFATURA_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_EFATURA_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_TARIH_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_TARIH_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_STOK_SATIS_ADET_REYON_REPORT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_STOK_SATIS_ADET_REYON_REPORT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_SIPARIS_BILGILERI_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_SIPARIS_BILGILERI_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_SIPARIS_BILGILERI]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_SIPARIS_BILGILERI]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_GRUP_DETAY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_GRUP_DETAY]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_HEDIYE_CEK_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_HEDIYE_CEK_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_HEDIYE_CEK]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_HEDIYE_CEK]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_LOG_CLEAR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_LOG_CLEAR]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_CARI_IBM_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_CARI_IBM_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_USER_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_USER_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_KASIYER_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_KASIYER_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BEKLETME_DETAY_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BEKLETME_DETAY_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_DETAY_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_DETAY_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_TEKRAR_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_TEKRAR_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_PROMOSYON_IBM_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_PROMOSYON_IBM_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_TUTAR_IBM_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_IBM_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_TUTAR_HEDEF_IBM_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_HEDEF_IBM_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_URUN_IBM_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_URUN_IBM_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_INDEX_REPAIR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_INDEX_REPAIR]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_AYLIK_MALI_REPORT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_AYLIK_MALI_REPORT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_MIKTAR_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_MIKTAR_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_MAIN_BROWSE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_MAIN_BROWSE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_EFATURA_TEMP_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_EFATURA_TEMP_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_EFATURA_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_EFATURA_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_KAR_HESAPLA]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_KAR_HESAPLA]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_MAIN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_MAIN]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_DEPARTMAN_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_DEPARTMAN_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_LIMIT_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_LIMIT_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_YETKI_TIP_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_YETKI_TIP_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_YETKI_TIP_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_YETKI_TIP_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_OZELKOD_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_OZELKOD_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_STOK_MAIN_BROWSE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_STOK_MAIN_BROWSE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_AYLIK_MALI_REPORT_EN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_AYLIK_MALI_REPORT_EN]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_KDV_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_KDV_INSERT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_KDV_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_KDV_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_HAREKET_IBM_LOG_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_HAREKET_IBM_LOG_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BEKLETME_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BEKLETME_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_STOK_MAIN_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_STOK_MAIN_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_FIS_DETAY_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_FIS_DETAY_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_URUN_BROWSE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_URUN_BROWSE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_URUN_IBM_BROWSE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_URUN_IBM_BROWSE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_URUN_IBM_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_URUN_IBM_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_FIS_DETAY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_FIS_DETAY]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_URUN_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_URUN_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_CARI_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_CARI_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_STOK_NOBONUS_TUTAR]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_STOK_NOBONUS_TUTAR]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_CARI_MAIN_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_CARI_MAIN_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_TUTAR_HEDEF_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_HEDEF_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_PROMOSYON_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_PROMOSYON_FILE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_REYON_PROMOSYON_R1]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_REYON_PROMOSYON_R1]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_REYON_PROMOSYON_R2]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_REYON_PROMOSYON_R2]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_REYON_PROMOSYON_R3]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_REYON_PROMOSYON_R3]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_REYON_PROMOSYON_R4]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_REYON_PROMOSYON_R4]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_URUN_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_URUN_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_HAREKET_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_HAREKET_LIST]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_XZ_REPORT_EN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_XZ_REPORT_EN]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_XZ_REPORT_TOPLAM]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_XZ_REPORT_TOPLAM]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_REYON_PROMOSYON_R6]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_REYON_PROMOSYON_R6]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BEKLETME_MAIN_INSERT_UPDATE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BEKLETME_MAIN_INSERT_UPDATE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_XZ_REPORT_EARCHIVE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_XZ_REPORT_EARCHIVE]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_XZ_REPORT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_XZ_REPORT]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_PROMOSYON_TUTAR_KONTROL]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_KONTROL]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_BEKLETME_DETAY_LIST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_BEKLETME_DETAY_LIST]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_BEKLETME_DETAY_LIST]  
	@FISID	INT,
	@FIYATTIPNO INT = 0
AS
	DECLARE @CARITIPI VARCHAR(1), @CARIKODU VARCHAR(20)
	
	SELECT @CARIKODU = CARIKODU FROM TBL_BEKLETME_MAIN
	WHERE ID = @FISID

	IF ISNULL(@CARIKODU,'') = '' 
		SET @CARITIPI = 'H'
	ELSE 
		SET @CARITIPI = NULL

	SELECT 
		PLUNO, 
		SUM(D.MIKTAR) AS MIKTAR, 
		CONVERT(TINYINT, @FIYATTIPNO) AS FIYATTIPNO 
	INTO #STOK 
	FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
	WHERE FISID = @FISID
	GROUP BY PLUNO
	
	IF @FIYATTIPNO = 1
	BEGIN
		SELECT * INTO #LIMIT FROM TBL_PROMOSYON_LIMIT WITH (NOLOCK) 
		WHERE PLUNO IN (SELECT PLUNO FROM #STOK)
		ORDER BY LIMIT DESC		

		SELECT S.PLUNO, MAX(L.LIMIT) AS MAXLIMITMIKTAR INTO #MAXLIMIT FROM #STOK S
			INNER JOIN #LIMIT AS L ON L.PLUNO = S.PLUNO
		WHERE 
			L.BASLANGICTARIHI <= GETDATE() AND
			L.BITISTARIHI >= GETDATE() AND
			L.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			S.MIKTAR >= LIMIT AND LIMIT > 0
		GROUP BY S.PLUNO
		
		UPDATE #STOK
		SET FIYATTIPNO = L.FIYATTIPI
		FROM #STOK S
			INNER JOIN #LIMIT AS L ON L.PLUNO = S.PLUNO
			INNER JOIN #MAXLIMIT AS M ON M.PLUNO = L.PLUNO AND M.MAXLIMITMIKTAR = L.LIMIT 
		WHERE 
			L.BASLANGICTARIHI <= GETDATE() AND
			L.BITISTARIHI >= GETDATE() AND
			L.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			S.MIKTAR >= LIMIT AND LIMIT > 0
		
		DROP TABLE #LIMIT
		DROP TABLE #MAXLIMIT
	END
		
	
	SELECT
		D.ID,
		D.FISID,
		D.SATIRNO,
		D.TIP,
		D.PLUNO,
		D.BARKOD,
		D.STOKKODU,
		D.STOKADI,
		D.KDV,
		D.DEPARTMAN,
		D.MIKTAR,
		D.BIRIM,
		CASE WHEN
				ISNULL(
						CASE
							WHEN L.FIYATTIPNO = 0 THEN D.FIYAT
							WHEN L.FIYATTIPNO = 1 THEN S.FIYAT
							WHEN L.FIYATTIPNO = 2 THEN S.FIYAT2
							WHEN L.FIYATTIPNO = 3 THEN S.FIYAT3
						END,D.FIYAT) = 0
			THEN D.FIYAT
		ELSE
			ISNULL(
					CASE
						WHEN L.FIYATTIPNO = 0 THEN D.FIYAT
						WHEN L.FIYATTIPNO = 1 THEN S.FIYAT
						WHEN L.FIYATTIPNO = 2 THEN S.FIYAT2
						WHEN L.FIYATTIPNO = 3 THEN S.FIYAT3
					END,D.FIYAT)
		END AS FIYAT,
		CASE WHEN
				ISNULL(
				CASE
					WHEN L.FIYATTIPNO = 0 THEN D.TUTAR
					WHEN L.FIYATTIPNO = 1 THEN S.FIYAT  * D.MIKTAR
					WHEN L.FIYATTIPNO = 2 THEN S.FIYAT2 * D.MIKTAR
					WHEN L.FIYATTIPNO = 3 THEN S.FIYAT3 * D.MIKTAR
				END,D.TUTAR) = 0
			 THEN D.TUTAR
		ELSE
			ISNULL(
					CASE
						WHEN L.FIYATTIPNO = 0 THEN D.TUTAR
						WHEN L.FIYATTIPNO = 1 THEN S.FIYAT  * D.MIKTAR
						WHEN L.FIYATTIPNO = 2 THEN S.FIYAT2 * D.MIKTAR
						WHEN L.FIYATTIPNO = 3 THEN S.FIYAT3 * D.MIKTAR
					END,D.TUTAR)
		END AS TUTAR,
		CONVERT(FLOAT,0) AS TUTAR_1,
		D.INDYUZDE,
		D.INDTUTAR,
		D.ARTYUZDE,
		D.ARTTUTAR,
		D.KASIYERKODU,
		D.KASIYERADI,
		D.PLASIYERKODU,
		D.PLASIYERADI,
		D.ACIKLAMA,
		D.BARKODTYPE,
		D.DOVIZKODU,
		D.DOVIZKURU,
		D.DOVIZTUTARI,
		D.PUAN,
		D.TEVKIFATKODU,
		D.TEVKIFATACIKLAMA,
		D.TEVKIFATORANI,
		D.OTVKODU,
		D.OTVACIKLAMA,
		D.OTVORANI,
		ISNULL(S.ISINDIRIM,1) AS ISINDIRIM
	FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
		INNER JOIN #STOK L ON L.PLUNO = D.PLUNO
		LEFT JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
	WHERE
		D.FISID = @FISID
	ORDER BY D.ID

	DROP TABLE #STOK
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_KONTROL] 
	@CARITIPI		VARCHAR(1) ,
	@ARATOPLAM		FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 


DECLARE @NOBONUSTUTAR FLOAT

SELECT @NOBONUSTUTAR = SUM(TUTAR) 
FROM TBL_BEKLETME_DETAY
WHERE FISID IN (
				SELECT ID FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
				) AND
PLUNO IN (SELECT PLUNO FROM TBL_STOK_MAIN WHERE ISNULL(REYONADI,'') = 'NOBONUS')

SET @NOBONUSTUTAR = ISNULL(@NOBONUSTUTAR,0)

SET @ARATOPLAM = @ARATOPLAM - @NOBONUSTUTAR

DECLARE @CARIGRUP VARCHAR(255)

IF ISNULL(@CARIKODU,'') <> ''
	SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

SET @CARIGRUP = ISNULL(@CARIGRUP,'')

IF @CARITIPI = 'M' SET @CARITIPI = NULL

	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)
	
	IF @CARIGRUP = 'NOBONUS' 
	BEGIN
		SELECT * FROM #RETTABLE
	
		DROP TABLE #RETTABLE
		
		RETURN
	END
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA, PLUNO)
	SELECT  
		'15' AS INDIRIMTIPI,
		0,
		ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
		CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM',
		U.PLUNO
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.PLUNO 
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
	WHERE 
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		(
			CARIGRUP = @CARIGRUP OR
			CARIGRUP = ''
		) AND
		VREYONADI = '' AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) > 1  AND
		D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '15')
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA, PLUNO)
		SELECT  
			'15' AS INDIRIMTIPI,
			0,
			ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
			CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM',
			U.PLUNO
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.PLUNO 
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
		WHERE 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			CARIGRUP = '' AND
			VREYONADI = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) > 1  AND
			D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
		0,
		CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
		CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @ARATOPLAM AND 
		(
			CARIGRUP = @CARIGRUP OR
			CARIGRUP = ''
		) AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		PUAN = 0 AND
		ISNULL(PUANYUZDE,0) = 0
	ORDER BY ARATOPLAM DESC
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('05','07'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			0,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			CARIGRUP = '' AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			PUAN = 0 AND
			ISNULL(PUANYUZDE,0) = 0
		ORDER BY ARATOPLAM DESC
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT  
		TOP 1
		'09',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * (INDTUTAR) ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * (INDTUTAR) ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2)		
		 AS MONEY), 1)+' TL İND.',
		PUAN,
		U.VPLUNO
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT PLUNO, STOKADI, FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, FIYAT) AS S ON S.PLUNO = U.VPLUNO
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 0
	ORDER BY U.ARATOPLAM DESC


	SELECT 
		STOKADI,
		ARATOPLAM,
		INDYUZDE,
		INDTUTAR,
		VMIKTAR,
		D.MIKTAR AS SATILANMIKTAR,
		D.TUTAR AS SATILANFIYAT,
		D.TOPTUTAR AS SATILANTUTAR,
		FLOOR(@ARATOPLAM / U.ARATOPLAM) AS KATSAYI,
		VPLUNO
	INTO #TEMP FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 1
	ORDER BY U.ARATOPLAM DESC
	

	DECLARE
		@STOKADI VARCHAR(50), 
		@ARATOP FLOAT, 
		@INDIRIM FLOAT, 
		@VMIKTAR FLOAT, 
		@SATILANMIKTAR FLOAT, 
		@SATILANFIYAT FLOAT, 
		@SATILANTUTAR FLOAT, 
		@KATSAYI INT,
		@TOPARA FLOAT,
		@VPLUNO INT

	DECLARE CURRT CURSOR FAST_FORWARD FOR
	SELECT ARATOPLAM FROM #TEMP
	GROUP BY ARATOPLAM
	OPEN CURRT

	FETCH NEXT FROM CURRT
	INTO @TOPARA

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE CURR CURSOR FAST_FORWARD FOR
		SELECT STOKADI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, SATILANMIKTAR, SATILANFIYAT, SATILANTUTAR, KATSAYI, VPLUNO FROM #TEMP
		WHERE ARATOPLAM = @TOPARA AND SATILANMIKTAR >= VMIKTAR
		ORDER BY INDTUTAR DESC
		OPEN CURR

		FETCH NEXT FROM CURR
		INTO @STOKADI, @ARATOP, @INDYUZDE, @INDTUTAR, @VMIKTAR, @SATILANMIKTAR, @SATILANFIYAT, @SATILANTUTAR, @KATSAYI, @VPLUNO
	
		DECLARE @KALANKATSAYI INT

		SELECT TOP 1 @KALANKATSAYI = KATSAYI FROM #TEMP
		WHERE ARATOPLAM = @TOPARA

		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @KALANKATSAYI <= 0 BREAK
		
			SET @INDIRIM = 0

			IF @INDTUTAR > 0
			BEGIN
			
				IF @KALANKATSAYI >= @SATILANMIKTAR 
				BEGIN
					SET @INDIRIM = @SATILANMIKTAR  * @INDTUTAR
					SET @KALANKATSAYI = @KALANKATSAYI - @SATILANMIKTAR
				END
				ELSE
				BEGIN
					SET @INDIRIM = @KALANKATSAYI * @INDTUTAR
					SET @KALANKATSAYI = 0
					
				END
			END
			ELSE IF @INDYUZDE > 0
			BEGIN
				IF @KALANKATSAYI >= @SATILANMIKTAR
				BEGIN
					SET @INDIRIM = (@SATILANTUTAR * @INDYUZDE) / 100.00
					SET @KALANKATSAYI = @KALANKATSAYI - @SATILANMIKTAR
				END
				ELSE
				BEGIN
					SET @INDIRIM = ((@KALANKATSAYI * @SATILANFIYAT) * @INDYUZDE) / 100.00
					SET @KALANKATSAYI = 0
				END
			END

			IF @INDIRIM > 0
				INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
				SELECT 
					'09', 
					@INDYUZDE, 
					@INDIRIM, 
					CONVERT(VARCHAR, CAST(@ARATOP AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(@STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
					ROUND(@INDIRIM,2) AS MONEY), 1)+' TL İND.',
					0,
					@VPLUNO

			FETCH NEXT FROM CURR
			INTO @STOKADI, @ARATOP, @INDYUZDE, @INDTUTAR, @VMIKTAR, @SATILANMIKTAR, @SATILANFIYAT, @SATILANTUTAR, @KATSAYI, @VPLUNO
		END
	
		CLOSE CURR
		DEALLOCATE CURR

		FETCH NEXT FROM CURRT
		INTO @TOPARA
	END

	CLOSE CURRT
	DEALLOCATE CURRT

	DROP TABLE #TEMP
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('09'))
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT  
			TOP 1
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN,
			VPLUNO
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT  
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN,
			VPLUNO
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 1
		ORDER BY U.ARATOPLAM ASC
	
	END
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'10',
		U.INDYUZDE,
		CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END,
		CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ALIŞVERİŞİNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			U.INDTUTAR > 0 OR
			U.INDYUZDE > 0
		)
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('10'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'10',
			U.INDYUZDE,
			CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END,
			CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+'  REYONU ALIŞVERİŞİNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR  FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				U.INDTUTAR > 0 OR
				U.INDYUZDE > 0
			)
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'11',
		0,
		D.TUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR = 0 AND
		U.INDYUZDE = 0 
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'11',
			0,
			D.TUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR = 0 AND
			U.INDYUZDE = 0 
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
		0,
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
		CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN,
		A.PLUNO
	FROM (
			SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
			GROUP BY PLUNO
			HAVING SUM(MIKTAR) > 0
		) AS D 
		INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.PLUNO = D.PLUNO AND A.PLUNO = A.VPLUNO AND (A.CARIGRUP = @CARIGRUP OR A.CARIGRUP = '')
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = A.PLUNO
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0	AND
		A.VMIKTAR <> 0	
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('14','16'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT 
			CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
			0,
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
			CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN,
			A.PLUNO
		FROM (
				SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
				FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
					INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				GROUP BY PLUNO
				HAVING SUM(MIKTAR) > 0
			) AS D 
			INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.PLUNO = D.PLUNO AND A.PLUNO = A.VPLUNO AND A.CARIGRUP = ''
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = A.PLUNO
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0 AND
			A.VMIKTAR <> 0	
	
	CREATE TABLE #PROMOSYONTBL(APLUNO INT, VPLUNO INT, VREYONADI VARCHAR(20)  COLLATE TURKISH_CI_AS, AMIKTAR FLOAT, VMIKTAR FLOAT, ALINANMIKTAR FLOAT, VERILENMIKTAR FLOAT, VERILENBIRIMFIYAT FLOAT, PUAN FLOAT, SATIR INT, INDYUZDE FLOAT, INDTUTAR FLOAT)		

	INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT PLUNO, VPLUNO, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		(
			A.CARIGRUP = @CARIGRUP OR
			A.CARIGRUP = ''
		) AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
		A.PLUNO <> A.VPLUNO 
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 1)
		INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT PLUNO, VPLUNO, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.CARIGRUP = '' AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.PLUNO <> A.VPLUNO 
		
	INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT PLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P2' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
		(
			A.CARIGRUP = @CARIGRUP OR
			A.CARIGRUP = ''
		) AND
		ISNULL(VREYONADI,'') <> ''

	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 2)
		INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT PLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P2' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.CARIGRUP = '' AND
			ISNULL(VREYONADI,'') <> ''

	UPDATE #PROMOSYONTBL
	SET	VPLUNO = H.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.REYONADI  COLLATE TURKISH_CI_AS = P.VREYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = S.PLUNO
	WHERE P.VREYONADI <> ''
	
	UPDATE #PROMOSYONTBL
	SET ALINANMIKTAR = H.MIKTAR
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = P.APLUNO

	UPDATE #PROMOSYONTBL
	SET VERILENMIKTAR = H.MIKTAR,
		VERILENBIRIMFIYAT = CASE WHEN VERILENBIRIMFIYAT > 0 THEN VERILENBIRIMFIYAT ELSE H.BIRIMFIYAT END
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = P.VPLUNO

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'18',
		0,
		(CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								((CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END)) 
								AS MONEY
							)		 
						,1)
		+' TL İND',
		FLOOR(ALINANMIKTAR / AMIKTAR) * PUAN,
		V.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS A ON A.PLUNO = P.APLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS V ON V.PLUNO = P.VPLUNO
	WHERE 
		VMIKTAR = 0 AND
		ALINANMIKTAR <> 0 AND 
		VERILENMIKTAR <> 0 AND
		FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, V.PLUNO, A.STOKADI, INDYUZDE, INDTUTAR  	
	
	DELETE FROM #PROMOSYONTBL
	WHERE VMIKTAR = 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'17',
		0,
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								CASE 
									WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
										THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
										ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
									ELSE 0 
								END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END) AS MONEY
							)		 
						,1)
		+' TL İND',
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * PUAN,
		V.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS A ON A.PLUNO = P.APLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS V ON V.PLUNO = P.VPLUNO
	WHERE ALINANMIKTAR <> 0 AND VERILENMIKTAR <> 0 AND
		(CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END)) <> 0
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, A.STOKADI, INDYUZDE, V.PLUNO  	
		

	DROP TABLE #PROMOSYONTBL

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		--TOP 1 --MURAT
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND((T.TUTAR * INDYUZDE) / 100.00,2),
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN ÜRÜN ALANA '+CONVERT(VARCHAR, FLOOR(T.TUTAR / ARATOPLAM)*PUAN)+' PUAN HEDİYE',
		FLOOR(T.TUTAR / ARATOPLAM) * PUAN,
		NULL
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR > 0 AND
		ARATOPLAM > 0 AND 
		T.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR = 0 AND
		P.INDYUZDE = 0 AND 
		P.PUAN > 0
	ORDER BY P.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR > 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR > 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND((H.TUTAR * INDYUZDE) / 100.00,2),
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN '+STOKADI+' ALANA '+CONVERT(VARCHAR, CAST(ROUND((H.TUTAR * INDYUZDE) / 100.00,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		H.PLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, S.PLUNO, S.STOKADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.PLUNO, S.STOKADI, S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		T.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDYUZDE > 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		TOP 1
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR > 0
	ORDER BY P.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '28' ELSE '29' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, FLOOR(H.MIKTAR / P.AMIKTAR) * P.AMIKTAR)+' ADET ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM = 0 AND
		P.AMIKTAR > 0 AND
		P.VMIKTAR = 0 AND
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2) > 0 AND
		ISKADEMELI = 0
		

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.VMIKTAR * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		CASE WHEN P.VMIKTAR > L.MIKTAR THEN L.MIKTAR ELSE P.VMIKTAR END *
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(CASE WHEN P.VMIKTAR > L.MIKTAR THEN L.MIKTAR ELSE P.VMIKTAR END * ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR > 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		0,
		CASE 
			WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
		ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
		END,
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, (FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR))+' ADET ALANA '+
		CONVERT(VARCHAR, CAST( 
								CASE 
									WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
								ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
								END		
							AS MONEY), 1)+' TL İND.',
		(FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.MIKTAR) AS MIKTAR, MIN(FIYAT) AS FIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		AMIKTAR <> 0 AND 
		VMIKTAR <> 0 AND 
		H.MIKTAR >= AMIKTAR AND
		ISKADEMELI = 0 AND
		ARATOPLAM = 0 AND
		(
			(P.INDYUZDE <> 0) OR
			(P.INDTUTAR <> 0)
		)
		 
	--R1 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R1 @CARITIPI, @CARIGRUP

	--R2 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R2 @CARITIPI, @CARIGRUP

	--R3 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R3 @CARITIPI, @CARIGRUP

	--R4 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R4 @CARITIPI, @CARIGRUP

	--R5 PROMOSYONU ÜRÜN PROMOSYONU OLARAK ALINMIŞTIR

	--R6 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R6 @CARITIPI, @CARIGRUP, @ARATOPLAM

	IF EXISTS(
				SELECT TOP 1 1 FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
				INNER JOIN (
								SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
								FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
									INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
									INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
								GROUP BY S.REYONADI
							) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
				WHERE 
					P.BASLANGICTARIHI <= GETDATE() AND
					P.BITISTARIHI >= GETDATE() AND
					P.PROMOSYONTIPI = 'P7' AND 
					P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
					(
						P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
						ISNULL(P.CARIGRUP,'') = ''
					) AND
					P.REYONADI <> '' AND 
					VPLUNO = 0 AND 
					H.TUTAR >= ARATOPLAM AND
					ISKADEMELI = 1
			)
	BEGIN
		DECLARE @REYONADI		VARCHAR(20),
				@REYONINDYUZDE	FLOAT,
				@REYONINDTUTAR	FLOAT,
				@STOKPLUNO		INT,
				@STOKMIKTAR		FLOAT,
				@STOKFIYAT		FLOAT,
				@ADET			FLOAT
				
		
		CREATE TABLE #STABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PLUNO INT, FIYAT FLOAT, INDTUTAR FLOAT, SIRANO INT)

		DECLARE CURREYON CURSOR FAST_FORWARD FOR
		SELECT P.REYONADI, P.INDYUZDE, P.INDTUTAR FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		WHERE 
			P.BASLANGICTARIHI <= GETDATE() AND
			P.BITISTARIHI >= GETDATE() AND
			P.PROMOSYONTIPI = 'P7' AND 
			P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
			(
				P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
				ISNULL(P.CARIGRUP,'') = ''
			) AND
			P.REYONADI <> '' AND 
			VPLUNO = 0 AND 
			H.TUTAR >= ARATOPLAM AND
			ISKADEMELI = 1
		OPEN CURREYON
		
		FETCH NEXT FROM CURREYON
		INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE FROM #STABLE	
			
			DECLARE CURRSTOK CURSOR FAST_FORWARD FOR
			SELECT D.PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) / SUM(MIKTAR) AS FIYAT
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
			WHERE S.REYONADI = @REYONADI 
			GROUP BY D.PLUNO
			HAVING (SUM(MIKTAR) <> 0) AND (SUM(MIKTAR) - FLOOR(SUM(MIKTAR)) = 0)
			OPEN CURRSTOK
			
			FETCH NEXT FROM CURRSTOK
			INTO @STOKPLUNO, @STOKMIKTAR, @STOKFIYAT
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ADET = @STOKMIKTAR
				
				WHILE @ADET > 0 
				BEGIN
					INSERT INTO #STABLE(PLUNO, FIYAT, INDTUTAR, SIRANO)
					SELECT @STOKPLUNO, @STOKFIYAT, CASE WHEN @REYONINDYUZDE = 0 THEN @REYONINDTUTAR ELSE ROUND((@STOKFIYAT * @REYONINDYUZDE) / 100.00,2) END, 0
					
					SET @ADET = @ADET - 1
				END
			
				FETCH NEXT FROM CURRSTOK
				INTO @STOKPLUNO, @STOKMIKTAR, @STOKFIYAT
			END
			
			CLOSE CURRSTOK
			DEALLOCATE CURRSTOK
			
			UPDATE #STABLE
			SET SIRANO = H.SIRANO
			FROM #STABLE S
				INNER JOIN (SELECT ID, ROW_NUMBER() OVER(ORDER BY FIYAT DESC) AS SIRANO FROM #STABLE) AS H ON H.ID = S.ID
			
			DELETE FROM #STABLE 
			WHERE SIRANO % 2 <> 0

			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
			SELECT 
				'30',
				@REYONINDYUZDE,
				ROUND(INDTUTAR,2),
				SUBSTRING(M.STOKADI,1,20)+' KADEMELİ '+CONVERT(VARCHAR, CAST(INDTUTAR AS MONEY), 1)+' TL İND.',
				0,
				M.PLUNO
			FROM #STABLE S
				INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS M ON M.PLUNO = S.PLUNO
			WHERE INDTUTAR <> 0
			ORDER BY INDTUTAR DESC
			
			FETCH NEXT FROM CURREYON
			INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		END
		
		CLOSE CURREYON
		DEALLOCATE CURREYON		
		
		DROP TABLE #STABLE
	END
	
	DECLARE @TOPLAMINDIRIM FLOAT
	
	SELECT @TOPLAMINDIRIM  = SUM(INDTUTAR) FROM #RETTABLE
	
	SET @ARATOPLAM = @ARATOPLAM - ABS(ISNULL(@TOPLAMINDIRIM,0))
	
	IF @ARATOPLAM > 0
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			'27',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
				END
			END,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, 
						CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
							CASE 
								WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
								ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
							END
						END				
				)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			(
				CARIGRUP = @CARIGRUP OR
				CARIGRUP = ''
			) AND
			(
				PUAN > 0 OR
				ISNULL(PUANYUZDE,0) > 0
			) AND
			INDYUZDE = 0 AND
			INDTUTAR = 0
		ORDER BY ARATOPLAM DESC
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '27')
			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
			SELECT  
				TOP 1
				'27',
				INDYUZDE,
				ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
				CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
					CASE 
						WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
						ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
					END
				END,
				CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
				CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
					CONVERT(VARCHAR, 
						CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
							CASE 
								WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
								ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
							END
						END)+' PUAN'
				ELSE
					CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
				END
			FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			WHERE 
				ARATOPLAM <= @ARATOPLAM AND 
				BASLANGICTARIHI <= GETDATE() AND
				BITISTARIHI >= GETDATE() AND
				PROMOSYONTIPI = 'P1' AND 
				CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
				CARIGRUP = '' AND
				(
					PUAN > 0 OR
					ISNULL(PUANYUZDE,0) > 0
				) AND
				INDYUZDE = 0 AND
				INDTUTAR = 0
			ORDER BY ARATOPLAM DESC
	END

	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_XZ_REPORT]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL
AS


DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPFISNO IS NOT NULL
BEGIN
	DECLARE @TEKRARFISID INT, @ONCEKIFISNO INT
	
	SELECT @TMPSONTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE FISNO = @TMPFISNO AND TIP = @TMPTIP
	
	SELECT @ONCEKIFISNO = MAX(CONVERT(INT, FISNO))
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT, FISNO) < CONVERT(INT, @TMPFISNO) AND TIP = @TMPTIP
	
	SELECT @TMPILKTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT,FISNO) = @ONCEKIFISNO AND TIP = @TMPTIP
	
	IF @TMPILKTARIH IS NULL SET @TMPILKTARIH = GETDATE() - 365
END
ELSE
BEGIN
	IF @TMPTARIH IS NULL 
		SELECT TOP 1 @TMPTARIH = MAX(TARIH)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z'
	--	ORDER BY TARIH DESC

	IF @TMPFISNO IS NULL
		SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = @TMPTIP
	--	ORDER BY TARIH DESC

	SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
	SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

	IF @TMPILKTARIH IS NULL
		SET @TMPILKTARIH = @TMPTARIH
	IF @TMPSONTARIH IS NULL
		SET @TMPSONTARIH = GETDATE()
END




SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DÖKÜMÜ' ELSE 'FİŞ DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DÖKÜMÜ' ELSE 'FATURA DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İRSALİYE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'BELGE İPTALLERİ ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPKDV, KDVHRC, TOPLAM, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CASE 
		WHEN ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'') <> '' THEN
		ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'')
	ELSE 'KSM'+CONVERT(VARCHAR, D.DEPARTMAN)+' (%'+CONVERT(VARCHAR, D.KDV)+' KDV)' END AS ACIKLAMA,
	SUM((CASE WHEN D.BELGETIPI = 2 THEN -1 ELSE 1 END) * D.NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL D
WHERE D.BELGETIPI IN(0,1,2,8)
GROUP BY D.DEPARTMAN, D.KDV
ORDER BY D.DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET TAHSİLAT DÖKÜMÜ(SATIŞ-İADE)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99]-PUAN',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'

DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-TAHSİLAT TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-SATIŞ TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0),
	3


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'BRÜT TAHSİLAT DÖKÜMÜ(SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(ABS(D.TUTAR)) AS TUTAR,
	11
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99]-PUAN',
	SUM(ABS(D.INDTUTAR)) AS TUTAR,
	11
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,8) AND
	D.PROMOSYONTIPI = '99'

DECLARE @TMPBRUTAHSILATTOPLAMI DECIMAL(21,6), @TMPBRUTODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPBRUTAHSILATTOPLAMI = SUM(TUTAR) 
FROM #RETTABLE
WHERE TIP = 11
 
SELECT @TMPBRUTODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-BRÜT TAHSİLAT TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0),
	11

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-BRÜT SATIŞ TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPBRUTODEMETIPIINDIRIMI),0),
	11


IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA GİRİŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA ÇIKIŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İND.TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'ARA TOPLAM İND. ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS ADET 
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME TİPİ İND. ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	SUM(INDTUTAR) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PUAN HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS ADET FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'VER.HED.ÇEK TOP.['+CONVERT(VARCHAR, ISNULL(COUNT(ID),0))+']',
	SUM(ABS(TUTAR)) AS TUTAR,
	6
FROM TBL_HEDIYE_CEK HC WITH (NOLOCK) 
WHERE TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA GİRİŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA ÇIKIŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #NAKITODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
WHERE KREDINO = 0
GROUP BY FISID

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #ODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
GROUP BY FISID

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET NAKİT TOPLAMI',
	SUM(
		(CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0)
		-(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS NAKITTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT JOIN #NAKITODEME D ON  D.FISID=M.ID 
WHERE M.TIP<> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET CİRO',
	SUM(
		((CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0))-
		(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS CIROTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT OUTER JOIN #ODEME D ON  D.FISID=M.ID 
WHERE M.TIP <> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

DROP TABLE #NAKITODEME
DROP TABLE #ODEME

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'YEMEK ÇEKİ HARİÇ KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF DEĞERLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF KDV', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF TOPLAM', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_XZ_REPORT_EARCHIVE]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL
AS


DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPTARIH IS NULL 
	SELECT TOP 1 @TMPTARIH = MAX(TARIH)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = 'Z'
--	ORDER BY TARIH DESC

IF @TMPFISNO IS NULL
	SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = @TMPTIP
--	ORDER BY TARIH DESC

SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

IF @TMPILKTARIH IS NULL
	SET @TMPILKTARIH = @TMPTARIH
IF @TMPSONTARIH IS NULL
	SET @TMPSONTARIH = GETDATE()


IF @TMPFISNO IS NOT NULL
BEGIN
	DECLARE @TEKRARFISID INT, @ONCEKIFISNO INT
	
	SELECT @TMPSONTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE FISNO = @TMPFISNO AND TIP = @TMPTIP
	
	SELECT @ONCEKIFISNO = MAX(CONVERT(INT, FISNO))
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT, FISNO) < CONVERT(INT, @TMPFISNO) AND TIP = @TMPTIP
	
	SELECT @TMPILKTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT,FISNO) = @ONCEKIFISNO AND TIP = @TMPTIP
	
	IF @TMPILKTARIH IS NULL SET @TMPILKTARIH = GETDATE() - 365
END

SELECT * INTO #FISMAIN FROM TBL_FIS_MAIN WITH (NOLOCK)
WHERE ISNULL(EFATURAKODU,'') <> ''

SELECT * INTO #FISDETAY FROM TBL_FIS_DETAY WITH (NOLOCK)
SELECT * INTO #FISODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
SELECT * INTO #FISPROMOSYON FROM TBL_FIS_PROMOSYON WITH (NOLOCK)

SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM #FISDETAY D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM #FISDETAY D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'Z DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM #FISMAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DÖKÜMÜ' ELSE 'FİŞ DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM #FISMAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DÖKÜMÜ' ELSE 'FATURA DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İRSALİYE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'BELGE İPTALLERİ ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPKDV, KDVHRC, TOPLAM, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KSM'+CONVERT(VARCHAR, DEPARTMAN)+' (%'+CONVERT(VARCHAR, KDV)+' KDV)' AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2,8)
GROUP BY DEPARTMAN, KDV
ORDER BY DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAHSİLAT DÖKÜMÜ (SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3
FROM #FISODEME D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - PUAN',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3
FROM #FISPROMOSYON D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'



DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998] - TAHSİLAT TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999] - SATIŞ TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0),
	3

IF EXISTS(
			SELECT TOP 1 ID FROM #FISMAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA GİRİŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM #FISMAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA ÇIKIŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İND.TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'ARA TOPLAM İND. ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS ADET 
		FROM #FISMAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM #FISPROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM #FISPROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME TİPİ İND. ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	SUM(INDTUTAR) AS PTUTAR ,
	6
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PUAN HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS ADET FROM #FISMAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA GİRİŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA ÇIKIŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'YEMEK ÇEKİ HARİÇ KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM #FISODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF DEĞERLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF KDV', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF TOPLAM', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
DROP TABLE #FISMAIN
DROP TABLE #FISDETAY
DROP TABLE #FISODEME
DROP TABLE #FISPROMOSYON
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_BEKLETME_MAIN_INSERT_UPDATE]
	@ID				INT = NULL,
	@ISBEKLETME		BIT,
	@KASANO			INT,
	@BELGEKODU		VARCHAR(20),
	@TARIH			DATETIME,
	@TIP			TINYINT,
	@VERGINO		VARCHAR(20),
	@CARIKODU		VARCHAR(20),
	@CARIADI		VARCHAR(50),
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@ISEFATURA		BIT,
	@ALIAS			VARCHAR(MAX),
	@YETKILIKODU	VARCHAR(4) = NULL,
	@YETKILIADI		VARCHAR(20) = NULL	,
	@OKCNO			VARCHAR(20) = NULL
AS
	SET NOCOUNT ON
	IF ISNULL(@ID,0) = 0
	BEGIN
		IF @ISBEKLETME = 0
			IF EXISTS(SELECT TOP 1 ID FROM TBL_BEKLETME_MAIN WITH (NOLOCK) WHERE ISBEKLETME = 0)
			BEGIN
				DELETE FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
			END
	
		INSERT INTO TBL_BEKLETME_MAIN(ISBEKLETME, KASANO, BELGEKODU, TARIH, TIP, VERGINO, CARIKODU, CARIADI, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, ISEFATURA, ALIAS, YETKILIKODU, YETKILIADI, OKCNO)
		SELECT @ISBEKLETME, @KASANO, @BELGEKODU, @TARIH, @TIP, @VERGINO, @CARIKODU, @CARIADI, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @ISEFATURA, @ALIAS, @YETKILIKODU, @YETKILIADI, @OKCNO

		RETURN @@IDENTITY
	END
	ELSE
	BEGIN
		DELETE FROM TBL_BEKLETME_LOG WHERE FISID = @ID

		UPDATE TBL_BEKLETME_MAIN
		SET
			ISBEKLETME	= @ISBEKLETME	,
			KASANO		= @KASANO		,
			BELGEKODU	= @BELGEKODU	,
			TARIH		= @TARIH		,
			TIP			= @TIP			,
			VERGINO		= @VERGINO		,
			CARIKODU	= @CARIKODU		,
			CARIADI		= @CARIADI		,
			TUTAR		= @TUTAR		,
			INDYUZDE	= @INDYUZDE		,
			INDTUTAR	= @INDTUTAR		,
			ARTYUZDE	= @ARTYUZDE		,
			ARTTUTAR	= @ARTTUTAR		,
			KASIYERKODU	= @KASIYERKODU	,
			KASIYERADI	= @KASIYERADI	,
			ISEFATURA	= @ISEFATURA	,
			ALIAS		= @ALIAS		,
			YETKILIKODU	= @YETKILIKODU	,
			YETKILIADI	= @YETKILIADI	,
			OKCNO		= @OKCNO
		WHERE ID = @ID

		RETURN @ID
	END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_REYON_PROMOSYON_R6]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL,
	@ARATOPLAM		FLOAT
AS
SET NOCOUNT ON
	CREATE TABLE #REYONPROMOSYON(ID INT IDENTITY(1,1) PRIMARY KEY, ARATOPLAM FLOAT, REYONADI VARCHAR(20), VREYONADI VARCHAR(20), VMIKTAR FLOAT, INDYUZDE FLOAT, INDTUTAR FLOAT, ISOK BIT, ALIMKATSAYI INT)

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)
	
	INSERT INTO #REYONPROMOSYON(ARATOPLAM, REYONADI, VREYONADI, VMIKTAR, INDYUZDE, INDTUTAR, ISOK)
	SELECT 
		ARATOPLAM,
		REYONADI,
		VREYONADI,
		VMIKTAR,
		INDYUZDE,
		INDTUTAR,
		0
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R6' AND
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 

SELECT MAX(R.ID) AS ID, FLOOR(SUM(D.TUTAR) / R.ARATOPLAM) AS ALIMKATSAYI
INTO #ALINANTBL FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
	INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	INNER JOIN #REYONPROMOSYON R WITH (NOLOCK) ON R.REYONADI = S.REYONADI
GROUP BY R.REYONADI, R.VREYONADI, R.ARATOPLAM
HAVING SUM(D.TUTAR) >= R.ARATOPLAM

UPDATE #REYONPROMOSYON
SET ISOK = 1,
	ALIMKATSAYI = A.ALIMKATSAYI
FROM #REYONPROMOSYON R
	INNER JOIN #ALINANTBL A ON A.ID = R.ID

DELETE FROM #REYONPROMOSYON
WHERE ISOK = 0

UPDATE #REYONPROMOSYON
SET ISOK = 0

SELECT 
	R.ARATOPLAM, 
	R.REYONADI, 
	R.VREYONADI, 
	R.VMIKTAR, 
	CASE 
		WHEN R.INDTUTAR > 0 THEN CASE WHEN FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) > ALIMKATSAYI THEN ALIMKATSAYI ELSE FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) END * R.INDTUTAR
	ELSE ((CASE WHEN FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) > ALIMKATSAYI THEN ALIMKATSAYI ELSE FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) END  * AVG(D.FIYAT)) * R.INDYUZDE) / 100.00 
	END AS INDTUTAR
INTO #VERILENTBL FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
	INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	INNER JOIN #REYONPROMOSYON R WITH (NOLOCK) ON R.VREYONADI = S.REYONADI
GROUP BY R.ARATOPLAM, R.REYONADI, R.VREYONADI, R.VMIKTAR, R.INDTUTAR, R.INDYUZDE, ALIMKATSAYI
HAVING SUM(D.MIKTAR) >= R.VMIKTAR




INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
SELECT 
	'25',
	0,
	INDTUTAR,
	SUBSTRING(REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL ALIM VE '+ 
	SUBSTRING(VREYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, VMIKTAR)+' ADET VE ÜSTÜ ALIMA '+
	CONVERT(VARCHAR, CAST(INDTUTAR AS MONEY),1)+' TL İNDİRİM',
	0,
	NULL
FROM #VERILENTBL

SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE

DROP TABLE #ALINANTBL
DROP TABLE #VERILENTBL
DROP TABLE #REYONPROMOSYON
DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[SP_XZ_REPORT_TOPLAM]
	@TIP		VARCHAR(1),
	@KASANO		INT = 1,
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL
AS
DECLARE @TARIH DATETIME, @FISNO	VARCHAR(6)

SELECT TOP 1 @TARIH = MAX(TARIH), @FISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
FROM TBL_XZ_LOG WITH (NOLOCK)
WHERE TIP = @TIP

SET @TARIH = ISNULL(@TARIH, GETDATE()-365)
SET @FISNO = ISNULL(@FISNO, '000001')

IF @ILKTARIH IS NULL
	SET @ILKTARIH = @TARIH
IF @SONTARIH IS NULL
	SET @SONTARIH = GETDATE()

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH


SELECT
	@FISNO AS FISNO,
	ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 0 END) * NETTUTAR)) AS IADETOPLAM,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
	CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2,8)

DROP TABLE #DETAYTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_XZ_REPORT_EN]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL
AS

DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPTARIH IS NULL 
	SELECT TOP 1 @TMPTARIH = MAX(TARIH)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = 'Z'
--	ORDER BY TARIH DESC

IF @TMPFISNO IS NULL
	SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = @TMPTIP
--	ORDER BY TARIH DESC

SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

IF @TMPILKTARIH IS NULL
	SET @TMPILKTARIH = @TMPTARIH
IF @TMPSONTARIH IS NULL
	SET @TMPSONTARIH = GETDATE()

SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DETAILS' ELSE 'RECEIPT DETAILS' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOTAL,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TAXTOTAL,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS TAXEXCL,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS QUANTITY
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOTAL, TAXTOTAL, TAXEXCL, QUANTITY)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DETAILS' ELSE 'INVOICE DETAILS' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOTAL,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TAXTOTAL,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS TAXEXCL,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS QUANTITY
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOTAL, TAXTOTAL, TAXEXCL, QUANTITY)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'WAYBILL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOTAL,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TAXTOTAL,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS TAXEXCL,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS QUANTITY
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOTAL, TAXTOTAL, TAXEXCL, QUANTITY)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'RETURN DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOTAL,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TAXTOTAL,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS TAXEXCL,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS QUANTITY
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOTAL, TAXTOTAL, TAXEXCL, QUANTITY)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CANCEL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'CANCEL DOCUMENTS ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'CANCEL LINES ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOTAL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TAXTOTAL,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS TAXEXCL,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOTAL,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS QUANTITY
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TAXTOTAL, TAXEXCL, TOTAL, QUANTITY)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAX DEPARTMENT DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CASE 
		WHEN ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'') <> '' THEN
		ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'')
	ELSE 'DPT'+CONVERT(VARCHAR, D.DEPARTMAN)+' (%'+CONVERT(VARCHAR, D.KDV)+' TAX)' END AS ACIKLAMA,
	SUM((CASE WHEN D.BELGETIPI = 2 THEN -1 ELSE 1 END) * D.NETTUTAR) AS TOTAL,
	2
FROM #DETAYTBL D
WHERE D.BELGETIPI IN(0,1,2,8)
GROUP BY D.DEPARTMAN, D.KDV
ORDER BY D.DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAX DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' TAX',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOTAL,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET PAYMENT DETAILS (SALES-RETURN)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99]-BONUS',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'

DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-PAYMENT TOTAL',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-SALES TOTAL',
	ISNULL(@TMPTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'GROSS PAYMENTS DETAILS(SALES)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END,
	SUM(ABS(D.TUTAR)) AS TUTAR,
	11
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99]-BONUS',
	SUM(ABS(D.INDTUTAR)) AS TUTAR,
	11
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,8) AND
	D.PROMOSYONTIPI = '99'

DECLARE @TMPBRUTAHSILATTOPLAMI DECIMAL(21,6), @TMPBRUTODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPBRUTAHSILATTOPLAMI = SUM(TUTAR) 
FROM #RETTABLE
WHERE TIP = 11
 
SELECT @TMPBRUTODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-GROSS PAYMENT TOTAL',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0),
	11

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-GROSS SALES TOTAL',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPBRUTODEMETIPIINDIRIMI),0),
	11


IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CUSTOMER CASH PAYMENT DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PAYEE CASH PAYMENT DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'OTHER DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'LINE DISC.TOTAL   ['+CONVERT(VARCHAR, ISNULL(SUM(QUANTITY),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS QUANTITY
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SUBTOTAL DISC. ['+CONVERT(VARCHAR, ISNULL(SUM(QUANTITY),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS QUANTITY 
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PAYMENT DISCOUNT ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	SUM(INDTUTAR) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'BONUS USED  ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'DISCOUNT TOTAL  ['+CONVERT(VARCHAR, ISNULL(SUM(QUANTITY),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS QUANTITY
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS QUANTITY FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'GIVEN CHEQES TOTAL['+CONVERT(VARCHAR, ISNULL(COUNT(ID),0))+']',
	SUM(ABS(TUTAR)) AS TUTAR,
	6
FROM TBL_HEDIYE_CEK HC WITH (NOLOCK) 
WHERE TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'CASH RECEIVED TOTAL',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'CASH GIVEN TOTAL',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #NAKITODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
WHERE KREDINO = 0
GROUP BY FISID

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #ODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
GROUP BY FISID

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET CASH TOTAL',
	SUM(
		(CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0)
		-(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS NAKITTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT JOIN #NAKITODEME D ON  D.FISID=M.ID 
WHERE M.TIP<> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET SALES TOTAL',
	SUM(
		((CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0))-
		(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS CIROTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT OUTER JOIN #ODEME D ON  D.FISID=M.ID 
WHERE M.TIP <> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

DROP TABLE #NAKITODEME
DROP TABLE #ODEME

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'MEAL TICKET EXCLUDED TAX DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' TAX',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOTAL,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CUMULATIVE TOTAL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CUMULATIVE TAX', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CUMULATIVE TOTAL', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_HAREKET_LIST]
	@TIP	VARCHAR(2) = NULL, --HR, HD, HI
	@KASANO	INT = NULL,
	@TARIH	SMALLDATETIME = NULL,
	@INTERFORMAT	BIT = NULL,
	@REMOVEBARPOSFORMATS BIT = NULL,
	@ISMAXMIKTAR	BIT = NULL
AS
	SET DATEFORMAT mdy; 

	IF  @TIP IS NULL
	BEGIN
		SET @TIP = 'HR'
		SET @KASANO = 1
		SET @TARIH = '03/28/2024'
		SET @REMOVEBARPOSFORMATS = 0
		SET @INTERFORMAT = 0
		SET @ISMAXMIKTAR=1
	END

DECLARE
	@AY		INT,
	@YIL	INT,
	@GUN	INT

SELECT
	@GUN	= DATEPART(DD, @TARIH),
	@AY		= DATEPART(MM, @TARIH),
	@YIL	= DATEPART(YY, @TARIH)

CREATE TABLE #HRTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, BELGEID INT, TIP INT, SATIRNO INT, PLASIYERKODU VARCHAR(4), DATA VARCHAR(MAX), TARIH DATETIME, TOPLAM FLOAT, CARIKODU VARCHAR(20), TIPNO INT, YETKILIKODU VARCHAR(4), YETKILIADI VARCHAR(20), EFATURAKODU VARCHAR(20), UUID VARCHAR(50), ISEFATURA BIT)
IF @TIP = 'TO'
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 6 THEN 'T,N,00,'
				WHEN 7 THEN 'O,N,00,'
			END+
			dbo.SR(CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END,20)+','+
			dbo.SR(BELGEKODU,20)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		TIP IN (6, 7)

	SELECT DATA FROM #HRTABLE
END
ELSE
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, YETKILIKODU, YETKILIADI, EFATURAKODU, UUID, ISEFATURA)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 0 THEN '01,FIS'
				WHEN 1 THEN '02,FAT'
				WHEN 8 THEN '46,IRS'
				WHEN 2 THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 1 THEN '24,GPS' ELSE '21,FAT' END
			ELSE '01,FIS' END+','+
			dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+'     '+
			dbo.ZL(KASIYERKODU,4)+','+
			dbo.ZL(CONVERT(VARCHAR,BELGEKODU),6)+'  '+
			dbo.ZL(CONVERT(VARCHAR,KASIYERKODU),4),
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1, 
		YETKILIKODU, 
		YETKILIADI,
		EFATURAKODU,
		UUID,
		ISEFATURA
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		(
		((@TIP = 'HR') AND (TIP IN (0, 1, 8))) OR
		(((@TIP = 'HD') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 0)) OR
		(((@TIP = 'HR') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 1)) OR
		((@TIP = 'HI') AND (TIP IN (3)))
		)


	CREATE TABLE #DETAY(ID INT, PLUNO INT, BARKOD VARCHAR(20), ISDELETE BIT)

	INSERT INTO #DETAY(ID, PLUNO, BARKOD, ISDELETE)
	SELECT ID, PLUNO, BARKOD, 0
	FROM TBL_FIS_DETAY D
	WHERE D.FISID IN (SELECT ID FROM #HRTABLE)

	UPDATE #DETAY
	SET ISDELETE = 1
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN S ON S.BARKOD = D.BARKOD

	DELETE FROM #DETAY	WHERE ISDELETE = 1

	UPDATE #DETAY SET ISDELETE = 1

	UPDATE #DETAY
	SET BARKOD = M.BARKOD,
		ISDELETE = 0
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN M ON M.PLUNO = D.PLUNO

	DELETE FROM #DETAY WHERE ISDELETE = 1

	UPDATE TBL_FIS_DETAY
	SET BARKOD = D.BARKOD
	FROM TBL_FIS_DETAY F WITH (NOLOCK)
		INNER JOIN #DETAY D ON D.ID = F.ID

	DROP TABLE #DETAY

	SELECT FISID
	INTO #ODEME FROM TBL_FIS_ODEME
	WHERE 
		FISID IN (SELECT BELGEID FROM #HRTABLE) AND 
		KREDINO = 39
	GROUP BY FISID

	IF @TIP = 'HR'
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO)
		SELECT
			ID,
			TIP,
			9999999,
				CASE TIP
					WHEN 4 THEN '13,KGR'
				ELSE '12,KCK' END+',000000'+
				dbo.ZL(CONVERT(VARCHAR,BELGEKODU),4)+'00,'+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
			TARIH,
			TUTAR,
			CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
			1
		FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE
			KASANO = @KASANO AND
			DATEPART(DD, TARIH) = @GUN AND
			DATEPART(MM, TARIH) = @AY AND
			DATEPART(YY, TARIH) = @YIL AND
			TIP IN (4, 5)
	END

	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		TIP,
		2,
		'03,TAR,'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(DD, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(MM, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(YY, TARIH)),4)+'  ,'+
		dbo.SR(LEFT(CONVERT(VARCHAR, TARIH, 114),8),12),
		2
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
	SELECT
		D.FISID,
		MIN(SATIRNO)+2,
			CASE D.TIP
				WHEN 'SAT' THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN CASE WHEN M.TIP = 2 THEN '05' ELSE '04' END ELSE CASE WHEN M.TIP = 2 THEN '25' ELSE '04' END END
				WHEN 'IPT' THEN '05'
			ELSE '04' END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN D.TIP ELSE CASE WHEN M.TIP = 2 THEN CASE WHEN D.TIP = 'SAT' THEN 'GAL' ELSE 'IPT' END ELSE D.TIP END END+','+
			dbo.ZL(CONVERT(VARCHAR, 
									CASE 
										WHEN ABS(SUM(MIKTAR)) < 99.999 THEN CONVERT(DECIMAL(5,3), ROUND(ABS(SUM(MIKTAR)),3,1)) 
										WHEN ABS(SUM(MIKTAR)) < 999.99 THEN CONVERT(DECIMAL(5,2), ROUND(ABS(SUM(MIKTAR)),2,1)) 
										WHEN ABS(SUM(MIKTAR)) < 9999.9 THEN CONVERT(DECIMAL(5,1), ROUND(ABS(SUM(MIKTAR)),1,1)) 
										WHEN ABS(SUM(MIKTAR)) < 99999 THEN CONVERT(DECIMAL(5,0), ROUND(ABS(SUM(MIKTAR)),0,1)) 
									ELSE CONVERT(DECIMAL(5,3), ABS(SUM(MIKTAR))) END),6)+
			dbo.ZL(CONVERT(VARCHAR,PLUNO),6)+','+
			dbo.ZL(CONVERT(VARCHAR,DEPARTMAN),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(SUM(D.TUTAR)))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(SUM(D.TUTAR)) AS money), 0),10) END,
			D.PLASIYERKODU,
			3
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND D.TIP IN ('SAT', 'IPT')
	GROUP BY D.FISID, M.TIP, D.TIP, D.PLUNO, D.BARKOD, D.DEPARTMAN, D.PLASIYERKODU 
	ORDER BY D.FISID, MIN(SATIRNO)

	IF (ISNULL(@INTERFORMAT,0) = 1)
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
		SELECT
			D.FISID,
			MIN(SATIRNO)+2,
				'38,BKD,'+
				dbo.SR(SUBSTRING(BARKOD,1,12),12)+','+dbo.SR(SUBSTRING(BARKOD,13,8),12),
				D.PLASIYERKODU,
				4
		FROM TBL_FIS_DETAY D WITH (NOLOCK)
		WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT', 'IPT')
		GROUP BY D.FISID, D.TIP, D.BARKOD, D.PLASIYERKODU
		ORDER BY D.FISID


		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> '' AND TIPNO = 3
	END
	ELSE
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> ''  AND TIPNO = 3


	SELECT MIN(ID) AS ID, D.FISID, D.PLUNO, MIN(SATIRNO) AS SATIRNO, CONVERT(VARCHAR(10), '') AS KASIYERKODU
	INTO #FISDETAY FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') 
	GROUP BY D.FISID, D.PLUNO
	ORDER BY D.FISID, MIN(SATIRNO)
	
	UPDATE  #FISDETAY
	SET KASIYERKODU = D.KASIYERKODU
	FROM #FISDETAY F
		INNER JOIN TBL_FIS_DETAY D WITH (NOLOCK) ON D.ID = F.ID

	SELECT FISID, ISNULL(PLUNO,0) AS PLUNO, SUM(INDTUTAR) AS INDTUTAR INTO #PROMOSYON FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
	WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
	GROUP BY FISID, ISNULL(PLUNO,0)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		D.SATIRNO+2,
			'06'+',IND,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			6
	FROM #FISDETAY D
		INNER JOIN #PROMOSYON P ON P.FISID = D.FISID AND P.PLUNO = D.PLUNO

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		SATIRNO+2,
			'39'+',ART,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		7
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') AND ARTTUTAR <> 0
	ORDER BY D.FISID, D.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'06'+',IND,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			8
	FROM TBL_FIS_MAIN F WITH (NOLOCK)
		INNER JOIN #PROMOSYON P ON P.FISID = F.ID AND P.PLUNO = 0
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND P.INDTUTAR <> 0
	ORDER BY ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'39'+',ART,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		8
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND ARTTUTAR <> 0
	ORDER BY ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			10001,
				'53'+',PRM,'+ dbo.ZL(P.PROMOSYONTIPI,2)+'    '+CASE WHEN ISNULL(PLUNO,0) > 0 THEN dbo.ZL(CONVERT(VARCHAR, PLUNO),6) ELSE '      ' END+','+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			9
		FROM TBL_FIS_PROMOSYON P WITH (NOLOCK)
			INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = P.FISID
		WHERE P.FISID IN (SELECT BELGEID FROM #HRTABLE) 
		ORDER BY P.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		20001,
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN '08,TOP,            ,'
		ELSE CASE WHEN TIP = 3 THEN '30,FIP,           0,' ELSE '08,TOP,            ,' END END
		+
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),MAX(ABS(TOPLAM)))*100,0))),12)
		ELSE dbo.SL(CONVERT(VARCHAR, CAST(MAX(ABS(TOPLAM)) AS money), 0),12) END,
		10
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)
	GROUP BY BELGEID, TIP

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		FISID,
		2000001+ID,
		CASE KREDINO
			WHEN 0 THEN '09,NAK,            ,'
		ELSE '10,KRD,          '+dbo.ZL(CONVERT(VARCHAR, KREDINO),2)+',' END+
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
		ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
		11
	FROM TBL_FIS_ODEME WITH (NOLOCK)
	WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
	ORDER BY FISID, ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT 
			H.BELGEID,
			A.SATIRNO,
			'77,ONY,'+
			dbo.SR(YETKILIKODU,4)+dbo.SR(SUBSTRING(YETKILIADI,1,8),8)+','+
			dbo.SR(SUBSTRING(YETKILIADI,9,12),12),
			12
		FROM #HRTABLE H
			INNER JOIN (
						SELECT
							BELGEID,
							MAX(SATIRNO)+1 AS SATIRNO
						FROM #HRTABLE
						GROUP BY BELGEID
					   ) AS A ON A.BELGEID = H.BELGEID
		WHERE ISNULL(YETKILIKODU,'') <> ''
	
	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'44,'+CASE WHEN ISNULL(ISEFATURA,0) = 1 THEN 'EFK' ELSE 'EAK' END+','+ 
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5) AND ISNULL(EFATURAKODU,'') <> ''
		GROUP BY BELGEID, ISNULL(ISEFATURA,0), ISNULL(EFATURAKODU,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'55,'+'UI1'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+2,
			'55,'+'UI2'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),21,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),33,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			3000001+K.ID,
			'77,'+'KDV'+','+ 
			dbo.ZL(CONVERT(VARCHAR, KDV),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVTUTAR))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVTUTAR) AS money), 0),10) END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVHARICTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVHARICTUTAR) AS money), 0),12) END,
			12
		FROM TBL_FIS_KDV K WITH (NOLOCK)
		WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
		ORDER BY FISID, KDV

	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		H.BELGEID,
		MAX(H.SATIRNO)+1,
		'11,SON,'+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),1,12),12)+','+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),13,8),8)+'   '+CASE WHEN O.FISID IS NULL THEN ' ' ELSE 'A' END,
		13
	FROM #HRTABLE H
		LEFT JOIN #ODEME O ON O.FISID = H.BELGEID
	WHERE ISNULL(H.TIP,0) NOT IN (4,5,10)
	GROUP BY H.BELGEID, ISNULL(H.CARIKODU,''), O.FISID

	IF @REMOVEBARPOSFORMATS = 0
		IF @TIP = 'HR'
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA,TIPNO)
		SELECT
			9999999+ID,
			9999999+ID,
			'16,ZRP,'+
			dbo.SR(CONVERT(VARCHAR, @TARIH, 103),12)+','+
			dbo.SR(SUBSTRING(CONVERT(VARCHAR, TARIH, 114),1,8),12),
			14
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z' AND TARIH >= @TARIH AND TARIH < @TARIH+1

	SELECT '1,'+dbo.ZL(CONVERT(VARCHAR, ROW_NUMBER() OVER(ORDER BY BELGEID, SATIRNO, TIPNO, DATA)),5)+ ',' + DATA AS DATA FROM #HRTABLE

	DROP TABLE #FISDETAY
	DROP TABLE #PROMOSYON
	DROP TABLE #ODEME
END


DROP TABLE #HRTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_PROMOSYON_URUN_KONTROL] 
	@CARITIPI		VARCHAR(1),
	@PLUNO			INT,
	@MIKTAR			FLOAT,
	@TUTAR			FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 

	DECLARE @CARIGRUP VARCHAR(20)

	IF ISNULL(@CARIKODU,'') <> ''
		SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
		WHERE CARIKODU = @CARIKODU

	SET @CARIGRUP = ISNULL(@CARIGRUP,'')

	IF @CARITIPI = 'M' SET @CARITIPI = NULL
	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	IF @CARIGRUP = 'NOBONUS' 
	BEGIN
		SELECT * FROM #RETTABLE
	
		DROP TABLE #RETTABLE
		
		RETURN
	END
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(@MIKTAR * PUAN),
		SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) WHERE ISNULL(ISINDIRIM,1) = 1 GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
	WHERE 
		U.PLUNO = @PLUNO AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		VREYONADI = '' AND
		CARIGRUP = @CARIGRUP AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) <= 1
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('03','01'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(@MIKTAR * PUAN),
			SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) WHERE ISNULL(ISINDIRIM,1) = 1 GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
		WHERE 
			U.PLUNO = @PLUNO AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			VREYONADI = '' AND
			CARIGRUP = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) <= 1
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('03','01'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT 
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(@MIKTAR * PUAN),
			SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
		FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) WHERE ISNULL(ISINDIRIM,1) = 1 GROUP BY PLUNO, STOKADI, REYONADI) AS S ON P.REYONADI = S.REYONADI
		WHERE 
			S.PLUNO = @PLUNO AND
			P.BASLANGICTARIHI <= GETDATE() AND
			P.BITISTARIHI >= GETDATE() AND
			P.PROMOSYONTIPI = 'R5' AND 
			P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
			(
				P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
				ISNULL(P.CARIGRUP,'') = ''
			) 


	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_REYON_PROMOSYON_R4]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		0,
		CASE 
			WHEN P.INDTUTAR > 0 THEN P.INDTUTAR
			ELSE (H.FIYAT * CASE WHEN P.INDYUZDE = 0 THEN 100.00 ELSE P.INDYUZDE END) / 100.00
		END,	
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN EN UCUZ ÜRÜNE '+
		CONVERT(VARCHAR, CAST( 
								CASE 
									WHEN P.INDTUTAR > 0 THEN P.INDTUTAR
									ELSE (H.FIYAT * CASE WHEN P.INDYUZDE = 0 THEN 100.00 ELSE P.INDYUZDE END) / 100.00
								END		
							AS MONEY), 1)+' TL İND.',
		0,
		(
			SELECT TOP 1 D.PLUNO FROM TBL_BEKLETME_DETAY D WITH (NOLOCK) 
				INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
			WHERE FISID = H.FISID AND S.REYONADI = H.REYONADI AND FIYAT = H.FIYAT
		) AS PLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT D.FISID, S.REYONADI, SUM(D.TUTAR) AS TUTAR, MIN(FIYAT) AS FIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY D.FISID, S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R4' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
	 	H.TUTAR >= P.ARATOPLAM  

	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_REYON_PROMOSYON_R3]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON
	CREATE TABLE #REYONPROMOSYON(REYONADI VARCHAR(20), VREYONADI VARCHAR(20), AMIKTAR DECIMAL(21,6), VMIKTAR DECIMAL(21,6), INDYUZDE FLOAT, INDTUTAR FLOAT)

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)
	
	INSERT INTO #REYONPROMOSYON(REYONADI, VREYONADI, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
	SELECT 
		REYONADI,
		VREYONADI,
		AMIKTAR, 
		VMIKTAR,
		INDYUZDE,
		INDTUTAR
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R3' AND
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 

SELECT R.REYONADI, R.VREYONADI, FLOOR(SUM(D.MIKTAR) / R.AMIKTAR) * R.VMIKTAR AS VERILMESIGEREKENMIKTAR, R.AMIKTAR, R.VMIKTAR, R.INDYUZDE, R.INDTUTAR
INTO #ALINANTBL FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
	INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	INNER JOIN #REYONPROMOSYON R WITH (NOLOCK) ON R.REYONADI = S.REYONADI
GROUP BY R.REYONADI, R.VREYONADI, R.AMIKTAR, R.VMIKTAR, R.INDYUZDE, R.INDTUTAR
HAVING SUM(D.MIKTAR) >= R.AMIKTAR

DECLARE @REYONADI VARCHAR(20), @VREYONADI VARCHAR(20), @VERILMESIGEREKENMIKTAR FLOAT, @AMIKTAR FLOAT, @VMIKTAR FLOAT, @KALANMIKTAR FLOAT, @INDYUZDE FLOAT, @INDTUTAR FLOAT
DECLARE @PLUNO INT, @STOKADI VARCHAR(255), @FIYAT FLOAT, @MIKTAR FLOAT, @INDIRIMTUTARI FLOAT

DECLARE CURR CURSOR FAST_FORWARD FOR
SELECT REYONADI, VREYONADI, VERILMESIGEREKENMIKTAR, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR FROM #ALINANTBL
OPEN CURR

FETCH NEXT FROM CURR
INTO @REYONADI, @VREYONADI, @VERILMESIGEREKENMIKTAR, @AMIKTAR, @VMIKTAR, @INDYUZDE, @INDTUTAR

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @KALANMIKTAR = @VERILMESIGEREKENMIKTAR
	
	DECLARE CURRV CURSOR FAST_FORWARD FOR
	SELECT D.PLUNO, S.STOKADI, D.FIYAT, SUM(D.MIKTAR) AS MIKTAR
	FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
		INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	WHERE S.REYONADI = @VREYONADI
	GROUP BY D.PLUNO, S.STOKADI, D.FIYAT
	HAVING SUM(D.MIKTAR) > 0
	ORDER BY D.FIYAT ASC
	OPEN CURRV

	FETCH NEXT FROM CURRV
	INTO @PLUNO, @STOKADI, @FIYAT, @MIKTAR

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @PROMOSYONMIKTARI FLOAT
		SET @PROMOSYONMIKTARI = 0

		IF @KALANMIKTAR > 0
		BEGIN
			IF @KALANMIKTAR >=  @MIKTAR
				SET @PROMOSYONMIKTARI = @MIKTAR
			ELSE 
				SET @PROMOSYONMIKTARI = @KALANMIKTAR
		
			SET @KALANMIKTAR = @KALANMIKTAR - @MIKTAR

			IF @INDTUTAR > 0
				SET @INDIRIMTUTARI = @INDTUTAR
			ELSE
				SET @INDIRIMTUTARI = ROUND((@PROMOSYONMIKTARI * @FIYAT) * CASE WHEN @INDYUZDE = 0 THEN 100.00 ELSE @INDYUZDE END / 100.00,2)

			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
			SELECT 
				'25',
				0,
				@INDIRIMTUTARI AS INDIRIMTUTARI,
				SUBSTRING(@REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, SUM(@AMIKTAR))+' ADET ALANA '+ @VREYONADI+' REYONUNDAN '+ CONVERT(VARCHAR, SUM(@VMIKTAR))+' ADET ÜRÜNDE '+CONVERT(VARCHAR, CAST(@INDIRIMTUTARI AS MONEY),1)+' TL İNDİRİM',
				0,
				@PLUNO
		END

		IF @KALANMIKTAR <= 0 BREAK
		FETCH NEXT FROM CURRV
		INTO @PLUNO, @STOKADI, @FIYAT, @MIKTAR
	END
	
	CLOSE CURRV
	DEALLOCATE CURRV


	
	FETCH NEXT FROM CURR
	INTO @REYONADI, @VREYONADI, @VERILMESIGEREKENMIKTAR, @AMIKTAR, @VMIKTAR, @INDYUZDE, @INDTUTAR
END

CLOSE CURR
DEALLOCATE CURR

SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE

DROP TABLE #ALINANTBL
DROP TABLE #REYONPROMOSYON
DROP TABLE #RETTABLE

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_REYON_PROMOSYON_R2]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		CASE WHEN P.INDTUTAR > 0 THEN P.INDTUTAR ELSE ROUND((T.TUTAR * INDYUZDE) / 100.00,2) END,
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN '+  CONVERT(VARCHAR, CAST(ROUND(P.ARATOPLAM,2) AS MONEY),1)+' TL ALANA '+P.VREYONADI+' RYN.DAN '+T.STOKADI+' ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN P.INDTUTAR > 0 THEN P.INDTUTAR ELSE ROUND((T.TUTAR * INDYUZDE) / 100.00,2) END,2) AS MONEY),1)+' TL İND.',
		0,
		T.PLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.PLUNO, S.STOKADI, S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.PLUNO, S.STOKADI, S.REYONADI
						HAVING SUM(D.MIKTAR) > 0
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.PLUNO, S.STOKADI, S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.PLUNO, S.STOKADI, S.REYONADI
						HAVING SUM(D.MIKTAR) > 0
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.VREYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R2' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		H.TUTAR >= ARATOPLAM 

	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_REYON_PROMOSYON_R1]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	CREATE TABLE #REYONPROMOSYON(REYONADI VARCHAR(20), AMIKTAR DECIMAL(21,6), VMIKTAR DECIMAL(21,6), INDYUZDE FLOAT, INDTUTAR FLOAT)
	
	INSERT INTO #REYONPROMOSYON(REYONADI, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
	SELECT 
		REYONADI,
		AMIKTAR, 
		VMIKTAR,
		INDYUZDE,
		INDTUTAR
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R1' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 
	
	IF EXISTS(SELECT TOP 1 * FROM #REYONPROMOSYON)
	BEGIN
		CREATE TABLE #INDIRIM(AREYONADI VARCHAR(20), INDIRIMTUTARI FLOAT, AMIKTAR FLOAT, VMIKTAR FLOAT)

		CREATE TABLE #FIS(
							ID INT IDENTITY(1,1) PRIMARY KEY, 
							REYONADI VARCHAR(20), 
							ASATISFIYAT FLOAT, 
							ASATISMIKTAR FLOAT, 
							ASATISTUTAR FLOAT, 
							AMIKTAR FLOAT, 
							VMIKTAR FLOAT, 
							INDYUZDE FLOAT, 
							INDTUTAR FLOAT
						)
		
		DECLARE
			@ID					INT, 
			@AREYONADI			VARCHAR(20),

			@ASATISFIYAT		FLOAT, 
			@ASATISMIKTAR		FLOAT, 
			@ASATISTUTAR		FLOAT, 

			@ALINACAKMIKTAR		FLOAT, 
			@VERILECEKMIKTAR	FLOAT, 
			@AKALANMIKTAR		FLOAT,
			@R1INDYUZDE			FLOAT,
			@R1INDTUTAR			FLOAT


		INSERT INTO #FIS(REYONADI, ASATISFIYAT, ASATISMIKTAR, ASATISTUTAR,  AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
		SELECT 
			S.REYONADI,
			D.FIYAT,
			SUM(D.MIKTAR) AS MIKTAR,
			SUM(D.TUTAR) AS TUTAR,
			P.AMIKTAR,
			P.VMIKTAR,
			P.INDYUZDE,
			P.INDTUTAR
		FROM TBL_BEKLETME_DETAY D
			INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
			INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) S ON S.PLUNO = D.PLUNO
			INNER JOIN #REYONPROMOSYON P ON P.REYONADI COLLATE TURKISH_CI_AS = S.REYONADI 
		WHERE ISBEKLETME = 0
		GROUP BY S.REYONADI, D.FIYAT, P.AMIKTAR, P.VMIKTAR, P.INDYUZDE, P.INDTUTAR
		HAVING SUM(D.MIKTAR) > 0
		ORDER BY FIYAT DESC
		
		SET @AKALANMIKTAR = 0

		DECLARE CURR CURSOR FAST_FORWARD FOR
		SELECT 
			ID,
			REYONADI,
			ASATISFIYAT,
			ASATISMIKTAR,
			ASATISTUTAR,
			AMIKTAR,
			VMIKTAR,
			CASE WHEN INDYUZDE <= 0 THEN 100 ELSE INDYUZDE END,
			INDTUTAR
		FROM #FIS
		ORDER BY ASATISFIYAT DESC
		OPEN CURR

		FETCH NEXT FROM CURR
		INTO 
			@ID					,
			@AREYONADI			,
			@ASATISFIYAT		,
			@ASATISMIKTAR		,
			@ASATISTUTAR		,
			@ALINACAKMIKTAR		,
			@VERILECEKMIKTAR	,
			@R1INDYUZDE,
			@R1INDTUTAR

		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @AKALANMIKTAR = @AKALANMIKTAR + @ASATISMIKTAR

			WHILE @AKALANMIKTAR >= @ALINACAKMIKTAR 
			BEGIN
				INSERT INTO #INDIRIM(AREYONADI, INDIRIMTUTARI, AMIKTAR, VMIKTAR)
				SELECT @AREYONADI, CASE WHEN @R1INDTUTAR > 0 THEN @R1INDTUTAR ELSE ROUND(((@VERILECEKMIKTAR * @ASATISFIYAT) * @R1INDYUZDE / 100.00),2) END , @ALINACAKMIKTAR, @VERILECEKMIKTAR

				SET @AKALANMIKTAR = @AKALANMIKTAR - @ALINACAKMIKTAR
			END
	
			FETCH NEXT FROM CURR
			INTO 
				@ID					,
				@AREYONADI			,
				@ASATISFIYAT		,
				@ASATISMIKTAR		,
				@ASATISTUTAR		,
				@ALINACAKMIKTAR		,
				@VERILECEKMIKTAR	,
				@R1INDYUZDE,
				@R1INDTUTAR

		END

		CLOSE CURR
		DEALLOCATE CURR

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT 
			'25',
			0,
			SUM(INDIRIMTUTARI) AS INDIRIMTUTARI,
			SUBSTRING(AREYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, SUM(AMIKTAR))+' ADET ALANA '+CONVERT(VARCHAR, SUM(VMIKTAR))+' ADET ÜRÜNDE '+CONVERT(VARCHAR, CAST(ROUND(SUM(INDIRIMTUTARI),2) AS MONEY),1)+' TL İNDİRİM',
			0
		FROM #INDIRIM
		GROUP BY AREYONADI

		DROP TABLE #FIS
		DROP TABLE #INDIRIM		
	END
	
	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #REYONPROMOSYON
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_IMPORT_PROMOSYON_FILE]
AS

SET DATEFORMAT mdy 

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRAN

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, SUBSTRING(DATA,6,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,9,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,16,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,19,10),'.',''))/100 AS INDTUTAR,
			1 AS VMIKTAR,
			0 AS VPLUNO,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			SUBSTRING(DATA,74,20) AS REYONADI,
			CONVERT(INT, SUBSTRING(DATA,95,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,101,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP
		INTO #TEMPFILE FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P2'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	TRUNCATE TABLE TBL_PROMOSYON_URUN
	TRUNCATE TABLE TBL_PROMOSYON_TUTAR
	TRUNCATE TABLE TBL_PROMOSYON_REYON
	TRUNCATE TABLE TBL_PROMOSYON_LIMIT

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ISNULL(REYONADI,''), PUAN, CARIGRUP
		FROM #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	DROP TABLE #TEMPFILE 
	
	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,17,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,20,10),'.',''))/100 AS INDTUTAR,
			SUBSTRING(DATA,32,1) AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,74,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,80,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,101,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE2 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P1'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 0, 0, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, PUANYUZDE
		FROM #TEMPFILE2
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE2
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE2

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,27,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,31,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,46,2)+'-'+SUBSTRING(DATA,43,2)+SUBSTRING(DATA,48,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,66,2)+'-'+SUBSTRING(DATA,63,2)+SUBSTRING(DATA,68,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,83,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,89,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(BIT, SUBSTRING(DATA,110,1)) AS TUMURUNLER,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,112,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE3 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P4') AND CONVERT(INT, SUBSTRING(DATA,20,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, TUMURUNLER, PUANYUZDE
		FROM #TEMPFILE3
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE3
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE3

	BEGIN TRY
		SELECT
			'P4' AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,17,6)) AS VPLUNO,
			0 AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,79,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,85,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,105,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE4 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PF') AND CONVERT(INT, SUBSTRING(DATA,17,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, 0, PUANYUZDE
		FROM #TEMPFILE4
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE4
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE4

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			RTRIM(SUBSTRING(DATA,79,20)) AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,100,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,106,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, SUBSTRING(DATA,127,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,131,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE5 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PR') AND RTRIM(SUBSTRING(DATA,79,20)) <> ''
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE
		FROM #TEMPFILE5
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE5
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE5

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(INT, SUBSTRING(DATA,6,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,13,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,16,6)) AS VPLUNO,
			CONVERT(FLOAT, REPLACE(REPLACE(SUBSTRING(DATA,23,2),'--','0'),' ','0')) AS VMIKTAR, 
			CONVERT(FLOAT, SUBSTRING(DATA,26,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,29,10),'.',''))/100 AS INDTUTAR,
			CONVERT(DATETIME, SUBSTRING(DATA,44,2)+'-'+SUBSTRING(DATA,41,2)+SUBSTRING(DATA,46,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,64,2)+'-'+SUBSTRING(DATA,61,2)+SUBSTRING(DATA,66,14)) AS BITISTARIHI,
			'' AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,81,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,87,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP
		INTO #TEMPFILE6 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P3') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP
		FROM #TEMPFILE6
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE6
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE6

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			RTRIM(SUBSTRING(DATA,6,20)) AS REYONADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,38,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,42,10),'.',''))/100 AS INDTUTAR,
			CONVERT(INT, SUBSTRING(DATA,53,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,60,2)) AS VMIKTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,92,2)+'-'+SUBSTRING(DATA,89,2)+SUBSTRING(DATA,94,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,112,2)+'-'+SUBSTRING(DATA,109,2)+SUBSTRING(DATA,114,14)) AS BITISTARIHI,
			CONVERT(FLOAT, SUBSTRING(DATA,129,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,132,5)) AS PUAN,
			CONVERT(BIT, SUBSTRING(DATA,138,1)) AS ISKADEMELI,
			RTRIM(SUBSTRING(DATA,140,255)) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,396,20)) AS VREYONADI
		INTO #TEMPFILE7 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P7')  OR SUBSTRING(DATA,1,1) IN ('R')
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P7 VEYA R PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_REYON(PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, CARIGRUP, VREYONADI)
		SELECT
			PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, CARIGRUP, VREYONADI
		FROM #TEMPFILE7
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE7
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P VEYA R TBL_PROMOSYON_REYON TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE7

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(INT, SUBSTRING(DATA,6,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,6,20)) AS REYONADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,13,10),',','.')) AS LIMIT,
			CONVERT(INT, SUBSTRING(DATA,24,2)) AS FIYATTIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,30,2)+'-'+SUBSTRING(DATA,27,2)+SUBSTRING(DATA,32,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,50,2)+'-'+SUBSTRING(DATA,47,2)+SUBSTRING(DATA,52,14)) AS BITISTARIHI
		INTO #TEMPFILE8 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P8') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P8 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_LIMIT(BASLANGICTARIHI, BITISTARIHI, CARITIPI, PLUNO, LIMIT, FIYATTIPI)
		SELECT
			BASLANGICTARIHI, BITISTARIHI, CARITIPI, PLUNO, LIMIT, FIYATTIPI
		FROM #TEMPFILE8
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE8
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P8 TBL_PROMOSYON_LIMIT TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE8
COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_HEDEF_KONTROL] 
	@CARITIPI		VARCHAR(1) ,
	@ARATOPLAM		FLOAT,
	@ORAN			FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL,
	@ISARATOPLAMURUN BIT = NULL
AS


DECLARE @NOBONUSTUTAR FLOAT

SELECT @NOBONUSTUTAR = SUM(TUTAR) 
FROM TBL_BEKLETME_DETAY
WHERE FISID IN (
				SELECT ID FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
				) AND
PLUNO IN (SELECT PLUNO FROM TBL_STOK_MAIN WHERE ISNULL(REYONADI,'') = 'NOBONUS')

SET @NOBONUSTUTAR = ISNULL(@NOBONUSTUTAR,0)

SET @ARATOPLAM = @ARATOPLAM - @NOBONUSTUTAR

DECLARE @NEWARATOPLAM FLOAT 

SET @NEWARATOPLAM = @ARATOPLAM + ((@ARATOPLAM * @ORAN) / 100.00)

SET DATEFORMAT mdy; 

DECLARE @CARIGRUP VARCHAR(20)

IF ISNULL(@CARIKODU,'') <> ''
	SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

SET @CARIGRUP = ISNULL(@CARIGRUP,'')

IF @CARITIPI = 'M' SET @CARITIPI = NULL
	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	IF @CARIGRUP = 'NOBONUS' 
	BEGIN
		SELECT * FROM #RETTABLE
	
		DROP TABLE #RETTABLE
		
		RETURN
	END
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
		CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END,
		CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
			CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
		ELSE
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		END
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @NEWARATOPLAM AND 
		ARATOPLAM > @ARATOPLAM AND
		CARIGRUP = @CARIGRUP AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		PUAN = 0 AND
		ISNULL(PUANYUZDE,0) = 0
	ORDER BY ARATOPLAM DESC
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('05','07'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END,
			CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @NEWARATOPLAM AND 
			ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = '' AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			PUAN = 0 AND
			ISNULL(PUANYUZDE,0) = 0
		ORDER BY ARATOPLAM DESC
	
	IF ISNULL(@ISARATOPLAMURUN,0) = 0
	BEGIN	
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			--TOP 1
			'09',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
			LEFT JOIN (
							SELECT PLUNO, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO 
		WHERE 
			--U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = @CARIGRUP AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC
	END
	ELSE
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			--TOP 1
			'09',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
			LEFT JOIN (
							SELECT PLUNO, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO 
		WHERE 
			--U.ARATOPLAM <= @NEWARATOPLAM AND 
			--U.ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = @CARIGRUP AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC
	END

	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'09',
		U.INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (SELECT PLUNO, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		LEFT JOIN (
						SELECT PLUNO, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.VPLUNO 
	WHERE 
		--U.ARATOPLAM <= @NEWARATOPLAM AND 
		U.ARATOPLAM > @ARATOPLAM AND
		CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 1
	ORDER BY U.ARATOPLAM ASC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('09'))
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			--TOP 1
			'09',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
			LEFT JOIN (
							SELECT PLUNO, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO 
		WHERE 
			--U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC
	
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'09',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
			LEFT JOIN (
							SELECT PLUNO, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO 
		WHERE 
			--U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 1
		ORDER BY U.ARATOPLAM ASC
	END

	IF ISNULL(@ISARATOPLAMURUN,0) = 0
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			TOP 1
			'39',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			LEFT JOIN (
							SELECT PLUNO, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO 
			INNER JOIN (SELECT PLUNO, STOKADI, MAX(FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			CARIGRUP = @CARIGRUP AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI)  AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			D.PLUNO IS NULL
		ORDER BY U.ARATOPLAM DESC	

		IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('39'))
			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
			SELECT  
				TOP 1
				'39',
				U.INDYUZDE,
				ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2),
				CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
				PUAN
			FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
				LEFT JOIN (
								SELECT PLUNO FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
									INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								GROUP BY PLUNO
								HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO 
				INNER JOIN (SELECT PLUNO, STOKADI, MAX(FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
			WHERE 
				U.ARATOPLAM <= @ARATOPLAM AND 
				U.BASLANGICTARIHI <= GETDATE() AND
				U.BITISTARIHI >= GETDATE() AND
				CARIGRUP = '' AND
				U.PROMOSYONTIPI = 'P4' AND 
				U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
				(
					(U.INDTUTAR > 0) OR
					(U.INDYUZDE > 0)
				) AND
				D.PLUNO IS NULL
			ORDER BY U.ARATOPLAM DESC	
	END	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'10',
		U.INDYUZDE,
		CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (U.ARATOPLAM * INDYUZDE) / 100.00 END,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (U.ARATOPLAM * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		U.ARATOPLAM <= @NEWARATOPLAM AND 
		U.ARATOPLAM > @ARATOPLAM AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		CARIGRUP = @CARIGRUP AND
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			U.INDTUTAR > 0 OR
			U.INDYUZDE > 0
		)
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('10'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'10',
			U.INDYUZDE,
			CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (U.ARATOPLAM * INDYUZDE) / 100.00 END,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (U.ARATOPLAM * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			CARIGRUP = '' AND
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				U.INDTUTAR > 0 OR
				U.INDYUZDE > 0
			)
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'11',
		0,
		0,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL''YE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜ HEDİYE',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		U.ARATOPLAM <= @NEWARATOPLAM AND 
		U.ARATOPLAM > @ARATOPLAM AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		CARIGRUP = @CARIGRUP AND
		U.INDTUTAR = 0 AND
		U.INDYUZDE = 0 
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'11',
			0,
			0,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL''YE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜ HEDİYE',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			CARIGRUP = '' AND
			U.INDTUTAR = 0 AND
			U.INDYUZDE = 0 
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		'27' ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
		CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
				END
		END,
		CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
			CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
				END
		END)+' PUAN'
		ELSE
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		END
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @NEWARATOPLAM AND 
		ARATOPLAM > @ARATOPLAM AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		CARIGRUP = @CARIGRUP AND
		(
			PUAN > 0 OR
			ISNULL(PUANYUZDE,0) > 0
		) AND
		INDYUZDE = 0 AND
		INDTUTAR = 0
	ORDER BY ARATOPLAM DESC
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) > 0 THEN
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.'
		ELSE
		CONVERT(VARCHAR, PUAN) +' PUAN' END,
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR > 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR < ARATOPLAM AND
		H.TUTAR + ((H.TUTAR * @ORAN) / 100.00) >= ARATOPLAM 
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) > 0 THEN
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.'
		ELSE
		CONVERT(VARCHAR, PUAN) +' PUAN' END,
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR < ARATOPLAM AND
		H.TUTAR + ((H.TUTAR * @ORAN) / 100.00) >= ARATOPLAM 

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			'27' ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
					CASE 
						WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
						ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
					END
			END,
			CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, 
					CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
							CASE 
								WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
								ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
							END
					END				
				)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @NEWARATOPLAM AND 
			ARATOPLAM > @ARATOPLAM AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			CARIGRUP = '' AND
			(
				PUAN > 0 OR
				ISNULL(PUANYUZDE,0) > 0
			) AND
			INDYUZDE = 0 AND
			INDTUTAR = 0
		ORDER BY ARATOPLAM DESC
		
	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_MAIN_INSERT_UPDATE]
	@CARINO			INT = NULL,
	@CARIKODU		VARCHAR(20) = NULL,
	@CARIADI		VARCHAR(50) = NULL,
	@ADRES			VARCHAR(60) = NULL,
	@VERGIDAIRESI	VARCHAR(20) = NULL,
	@VERGINO		VARCHAR(20) = NULL,
	@INDIRIM		FLOAT = NULL,
	@GRUP			VARCHAR(20) = NULL,
	@FIYATTIPNO		TINYINT = NULL,
	@ISEFATURA		BIT = NULL,
	@EMAIL			VARCHAR(MAX) = NULL,
	@TELEFON		VARCHAR(20) = NULL,
	@CARITIPI		VARCHAR(1) = NULL,
	@ISUPDATE		BIT = NULL,
	@SUBEKODU		VARCHAR(20) = NULL
AS
	SET NOCOUNT ON

	DECLARE @ID INT, @CARINOID INT

	SELECT @ID = ID FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

	IF ISNULL(@CARINO,0) > 0
		SELECT @CARINOID = ID FROM TBL_CARI_MAIN WITH (NOLOCK)
		WHERE CARINO = @CARINO 
	
	IF ISNULL(@CARIKODU,'') <> ''
	BEGIN
		SELECT TOP 1 
			@INDIRIM = INDIRIM,
			@GRUP = GRUP,
			@CARITIPI = CARITIPI,
			@FIYATTIPNO = FIYATTIPNO
		FROM TBL_CARI_MAIN WITH (NOLOCK)
		WHERE CARIKODU = @CARIKODU
	END

	IF @ID IS NULL
	BEGIN
		SELECT @CARINO = MAX(CARINO) FROM TBL_CARI_MAIN WITH (NOLOCK)
		SET @CARINO = ISNULL(@CARINO,0) + 1
	END

	IF (ISNULL(@ID,0) <> ISNULL(@CARINOID,0)) AND (ISNULL(@ISUPDATE,0) = 0)
	BEGIN
		IF @ID IS NOT NULL
		BEGIN
			DELETE FROM TBL_CARI_MAIN
			WHERE ID = @ID
	
			SET @ID = NULL
		END

		IF @CARINOID IS NOT NULL
		BEGIN
			DELETE FROM TBL_CARI_MAIN
			WHERE ID = @CARINOID

			SET @ID = NULL
		END
	END

	IF ISNULL(@ID,0) = 0
		INSERT INTO TBL_CARI_MAIN(CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, TELEFON, CARITIPI, ISVERESIYE)
		SELECT @CARINO, @CARIKODU, @CARIADI, @ADRES, @VERGIDAIRESI, @VERGINO, @INDIRIM, @GRUP, GETDATE(), '0001', @FIYATTIPNO, @ISEFATURA, @EMAIL, @TELEFON, @CARITIPI, 1
	ELSE
		UPDATE TBL_CARI_MAIN
		SET
			CARIKODU		= ISNULL(@CARIKODU		, CARIKODU		),
			CARIADI			= ISNULL(@CARIADI		, CARIADI		),	
			ADRES			= ISNULL(@ADRES			, ADRES			),
			VERGIDAIRESI	= ISNULL(@VERGIDAIRESI	, VERGIDAIRESI	),
			VERGINO			= ISNULL(@VERGINO		, VERGINO		),
			INDIRIM			= ISNULL(@INDIRIM		, INDIRIM		),
			GRUP			= ISNULL(@GRUP			, GRUP			),
			FIYATTIPNO		= ISNULL(@FIYATTIPNO	, FIYATTIPNO	),
			ISEFATURA		= ISNULL(@ISEFATURA		, ISEFATURA		),
			EMAIL			= ISNULL(@EMAIL			, EMAIL			),
			TELEFON			= ISNULL(@TELEFON		, TELEFON		),
			CARITIPI		= ISNULL(@CARITIPI		, CARITIPI		)
		WHERE ID = @ID

	IF ISNULL(@SUBEKODU,'') <> ''
	BEGIN
		DECLARE @SUBECARIID INT

		SELECT @SUBECARIID = ID FROM TBL_SUBE_CARI WITH (NOLOCK) WHERE CARIKODU = @CARIKODU

		IF @SUBECARIID IS NULL
			INSERT INTO TBL_SUBE_CARI(SUBEID, CARIKODU)
			SELECT ID, @CARIKODU
			FROM TBL_SUBE WITH (NOLOCK)
			WHERE SUBEKODU = @SUBEKODU
		ELSE
			UPDATE TBL_SUBE_CARI
			SET SUBEID = (SELECT ID FROM TBL_SUBE WITH (NOLOCK) WHERE SUBEKODU = @SUBEKODU)
			WHERE CARIKODU = @CARIKODU
	END

	IF (ISNULL(@TELEFON,'') <> '') 
	BEGIN
		SET @TELEFON = REPLACE(@TELEFON,' ','')
		
		IF LEN(@TELEFON) >= 10 
		BEGIN
			IF (SUBSTRING(@TELEFON,1,1) = '5') SET @TELEFON = '90'+@TELEFON
			ELSE IF (SUBSTRING(@TELEFON,1,2) = '05') SET @TELEFON = '9'+@TELEFON

			IF SUBSTRING(@TELEFON,1,3) = '905'
			BEGIN
				DECLARE @TELEFONCARIKODU VARCHAR(20), @TELEFONID INT
				SELECT TOP 1 @TELEFONID = ID, @TELEFONCARIKODU = CARIKODU FROM TBL_CARI_TELEFON WITH (NOLOCK) WHERE TELEFON = @TELEFON

				IF ISNULL(@TELEFONCARIKODU,'') <> ''
					IF ISNULL(@CARIKODU,'') <> ''
						IF ISNULL(@TELEFONCARIKODU,'') <> ISNULL(@CARIKODU,'')
						BEGIN
							DELETE FROM TBL_CARI_TELEFON
							WHERE ID = @TELEFONID

							SET @TELEFONCARIKODU = ''
						END

				IF ISNULL(@TELEFONCARIKODU,'') = ''
				BEGIN
					INSERT INTO TBL_CARI_TELEFON(CARIKODU, TELEFON)
					SELECT @CARIKODU, @TELEFON
				END
			END
		END
	END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_STOK_NOBONUS_TUTAR]
AS
	SELECT SUM(TUTAR) AS TUTAR
	FROM TBL_BEKLETME_DETAY WITH (NOLOCK) 
	WHERE 
		FISID IN ( SELECT ID FROM TBL_BEKLETME_MAIN WHERE ISBEKLETME = 0) AND 
		PLUNO IN (
					SELECT PLUNO FROM TBL_STOK_MAIN WITH (NOLOCK)
					WHERE (ISNULL(REYONADI,'') = 'NOBONUS') OR (ISNULL(ISINDIRIM,1) = 0)
				)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_CARI_FILE]
	@ISDEGISEN BIT = 0
AS
SET NOCOUNT ON


DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRY
	SELECT
		CONVERT(TINYINT, SUBSTRING(DATA,1,1)) AS FIYATTIPNO,
		CONVERT(INT, SUBSTRING(DATA,2,6)) AS CARINO,
		RTRIM(SUBSTRING(DATA,8,20)) AS CARIKODU,
		RTRIM(SUBSTRING(DATA,28,20)) AS CARIADI,
		RTRIM(SUBSTRING(DATA,48,60)) AS ADRES,
		RTRIM(SUBSTRING(DATA,108,15)) AS VERGIDAIRESI,
		RTRIM(SUBSTRING(DATA,123,15)) AS VERGINO,
		CONVERT(INT, SUBSTRING(DATA,138,2)) AS INDIRIM,
		CASE WHEN LEN(DATA) <= 140 THEN CONVERT(BIT, 0) ELSE CONVERT(BIT, ISNULL(SUBSTRING(DATA,140,1),'0')) END AS ISEFATURA,
		CASE WHEN LEN(DATA) <= 140 THEN '' ELSE RTRIM(SUBSTRING(DATA,141,50)) END AS EMAIL,
		CASE WHEN LEN(DATA) <= 140 THEN 'S' ELSE RTRIM(SUBSTRING(DATA,191,1)) END AS CARITIPI,
		CASE WHEN LEN(DATA) <= 140 THEN '-' ELSE RTRIM(SUBSTRING(DATA,192,20)) END AS TELEFON,
		CASE WHEN LEN(DATA) <= 140 THEN 'GENEL' ELSE RTRIM(SUBSTRING(DATA,212,20)) END AS GRUP,
		CONVERT(BIT, CASE WHEN LEN(DATA) <= 140 THEN 1 ELSE CASE WHEN SUBSTRING(DATA,232,1) = '0' THEN 0 ELSE 1 END END) AS ISVERESIYE,
		CONVERT(BIT, 0) AS ISINSERTTELEFON,
		CONVERT(VARCHAR(20),'') CEPTELEFONU
	INTO #TEMPFILE FROM TBL_IMPORT_FILE
	WHERE LEN(DATA) >= 139

	UPDATE #TEMPFILE
	SET CEPTELEFONU = TELEFON

	UPDATE #TEMPFILE
	SET CEPTELEFONU = ''
	WHERE 
		(CEPTELEFONU NOT LIKE '905%' AND
		CEPTELEFONU NOT LIKE '5%' AND
		CEPTELEFONU NOT LIKE '05%') OR
		LEN(CEPTELEFONU) > 17 

	DELETE FROM #TEMPFILE
	WHERE CARIKODU IN (
						SELECT CARIKODU FROM #TEMPFILE
						GROUP BY CARIKODU
						HAVING COUNT(*) > 1
						)

	UPDATE #TEMPFILE
	SET CEPTELEFONU = REPLACE(CEPTELEFONU,' ', '')
	WHERE LEN(REPLACE(CEPTELEFONU,' ', '')) >= 10

	UPDATE #TEMPFILE
	SET CEPTELEFONU = CASE WHEN SUBSTRING(CEPTELEFONU,1,2) = '05' THEN '9'+CEPTELEFONU WHEN SUBSTRING(CEPTELEFONU,1,1) = '5' THEN '90'+CEPTELEFONU ELSE CEPTELEFONU END
	WHERE LEN(CEPTELEFONU) >= 10

	UPDATE #TEMPFILE
	SET CEPTELEFONU = ''
	WHERE CEPTELEFONU NOT LIKE '905%'
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : CARİ DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : CARI DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

BEGIN TRAN

	IF @ISDEGISEN = 1
		BEGIN TRY
			DELETE FROM TBL_CARI_MAIN
			WHERE CARINO IN (SELECT CARINO FROM #TEMPFILE)

			DELETE FROM TBL_CARI_TELEFON
			WHERE CARIKODU IN (SELECT CARIKODU FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH
	ELSE
	BEGIN
		TRUNCATE TABLE TBL_CARI_MAIN
		TRUNCATE TABLE TBL_CARI_TELEFON
	END

	BEGIN TRY
		INSERT INTO TBL_CARI_MAIN(CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, ISVERESIYE)
		SELECT CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, GETDATE(), APP_NAME(), FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, ISVERESIYE
		FROM  #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		SELECT C.ID, T.CARIKODU, REPLACE(T.CEPTELEFONU,' ','') AS TELEFON, CONVERT(BIT, 0) AS ISDELETE INTO #TMP 
		FROM #TEMPFILE T WITH (NOLOCK)
			INNER JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = T.CARIKODU
		WHERE LEN(REPLACE(T.CEPTELEFONU,' ','')) >= 10 

		UPDATE #TMP
		SET TELEFON = CASE WHEN SUBSTRING(TELEFON,1,2) = '05' THEN '9'+TELEFON WHEN SUBSTRING(TELEFON,1,1) = '5' THEN '90'+TELEFON ELSE TELEFON END

		UPDATE #TMP
		SET ISDELETE = 1
		FROM #TMP C
			INNER JOIN TBL_CARI_TELEFON T WITH (NOLOCK) ON T.CARIKODU = C.CARIKODU AND T.TELEFON = C.TELEFON

		DELETE FROM #TMP
		WHERE ISDELETE = 1

		INSERT INTO TBL_CARI_TELEFON(CARIKODU, TELEFON)
		SELECT CARIKODU, TELEFON FROM #TMP
		WHERE ID IN (
						SELECT MAX(ID) FROM #TMP
						WHERE 
							TELEFON LIKE '905%' AND
							LEN(TELEFON) = 12 AND
							TELEFON NOT LIKE '%[a-z][A-Z]%'
						GROUP BY TELEFON
					) AND 
			TELEFON NOT IN (SELECT TELEFON FROM TBL_CARI_TELEFON WITH (NOLOCK)) AND
			CARIKODU NOT IN (SELECT CARIKODU FROM TBL_CARI_TELEFON WITH (NOLOCK)) 

		DROP TABLE #TMP
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_TELEFON TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	IF ISNULL((SELECT COUNT(*) FROM TBL_CARI_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END

COMMIT TRAN

DROP TABLE #TEMPFILE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_IMPORT_URUN_FILE]
	@ISDEGISEN BIT = 0
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)
CREATE TABLE #TEMPFILE(
						PLUNO INT, 
						BARKOD VARCHAR(20), 
						STOKADI VARCHAR(50), 
						FIYAT FLOAT, 
						DEPARTMAN INT,
						BIRIM VARCHAR(4),
						TARTILI VARCHAR(1),
						FIYAT2 FLOAT,
						FIYAT3 FLOAT,
						DOVIZKODU VARCHAR(10),
						ALISDEPARTMAN INT,
						STOKKODU VARCHAR(20),
						REYONADI VARCHAR(20),
						RENK VARCHAR(50),
						BEDEN VARCHAR(20),
						MODELKODU VARCHAR(20),
						TEVKIFATKODU VARCHAR(10),
						TEVKIFATACIKLAMA VARCHAR(100),
						TEVKIFATORANI INT,
						OTVKODU VARCHAR(10),
						OTVACIKLAMA VARCHAR(100),
						OTVORANI INT,
						ALISFIYAT FLOAT,
						ISINDIRIM BIT
					)
BEGIN TRY
	
--IF EXISTS(
--				SELECT TOP 1 1 FROM TBL_IMPORT_FILE 
--				WHERE PATINDEX('%[Ã‡]%', DATA COLLATE Latin1_General_bin) > 0
--			)
--	UPDATE TBL_IMPORT_FILE
--	SET DATA = dbo.utf8_to_utf16(DATA)

	DECLARE @DATA VARCHAR(MAX)
	SELECT TOP 1 @DATA = DATA FROM TBL_IMPORT_FILE
	
	IF LEN(@DATA) <= 82
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,20)) AS STOKADI,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,10),'.',''))/100 
			ELSE CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,9),'.',''))/100 END AS FIYAT,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(INT, SUBSTRING(DATA,58,2)) 
			ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS DEPARTMAN,
			CASE WHEN LEN(DATA) = 65 THEN 
				RTRIM(SUBSTRING(DATA,60,4)) 
			ELSE
				RTRIM(SUBSTRING(DATA,59,4)) END AS BIRIM,
			
			CASE WHEN LEN(DATA) = 65 THEN 
				SUBSTRING(DATA,64,1)
			ELSE
				SUBSTRING(DATA,63,1) END AS TARTILI,
			0 AS FIYAT2,
			0 AS FIYAT3,
			'TL' AS DOVIZKODU,
			CASE WHEN LEN(DATA) = 65 THEN CONVERT(INT, SUBSTRING(DATA,58,2)) ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,8,20)) AS STOKKODU,
			'' AS REYONADI,
			'' AS RENK,
			'' AS BEDEN,
			'' AS MODELKODU,
			'' AS TEVKIFATKODU,
			'' AS TEVKIFATACIKLAMA,
			0  AS TEVKIFATORANI,
			'' AS OTVKODU,
			'' AS OTVACIKLAMA,
			0  AS OTVORANI,
			0 AS ALISFIYAT,
			1 AS ISINDIRIM
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63
	ELSE
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,50)) AS STOKADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,78,9),'.',''))/100 AS FIYAT,
			CONVERT(INT, SUBSTRING(DATA,87,2)) AS DEPARTMAN,
			RTRIM(SUBSTRING(DATA,89,4)) AS BIRIM,
			SUBSTRING(DATA,93,1) AS TARTILI,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,94,9),'.',''),'0')) / 100 AS FIYAT2,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,103,9),'.',''),'0')) / 100 AS FIYAT3,
			RTRIM(SUBSTRING(DATA,112,10)) AS DOVIZKODU,
			CONVERT(INT, SUBSTRING(DATA,122,2)) AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,124,20)) AS STOKKODU,
			RTRIM(SUBSTRING(DATA,144,20)) AS REYONADI,
			RTRIM(SUBSTRING(DATA,164,50)) AS RENK,
			RTRIM(SUBSTRING(DATA,214,20)) AS BEDEN,
			RTRIM(SUBSTRING(DATA,234,20)) AS MODELKODU,
			RTRIM(SUBSTRING(DATA,254,10)) AS TEVKIFATKODU,
			RTRIM(SUBSTRING(DATA,264,100)) AS TEVKIFATACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,364,3)) AS TEVKIFATORANI,
			RTRIM(SUBSTRING(DATA,367,10)) AS OTVKODU,
			RTRIM(SUBSTRING(DATA,377,100)) AS OTVACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,477,3)) AS OTVORANI,
			CONVERT(FLOAT, ISNULL(REPLACE(REPLACE(REPLACE(SUBSTRING(DATA,480,9),'.',''),CHAR(13),'0'),CHAR(10),'0'),'0'))/100 AS ALISFIYAT,
			CONVERT(BIT, CASE WHEN SUBSTRING(DATA,489,1) = '0' THEN 0 ELSE 1 END) AS ISINDIRIM
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : ÜRÜN DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

DELETE FROM #TEMPFILE
WHERE BARKOD IN (
                                                SELECT BARKOD FROM #TEMPFILE
                                                GROUP BY BARKOD
                                                HAVING COUNT(*) > 1
                                        )

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : URUN DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

DECLARE @DEPARTMAN INT

SELECT TOP 1 @DEPARTMAN = DEPARTMAN
FROM #TEMPFILE
WHERE DEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU DEPARTMAN TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

SET @DEPARTMAN = NULL

SELECT TOP 1 @DEPARTMAN = ALISDEPARTMAN
FROM #TEMPFILE
WHERE ALISDEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU ALIŞ DEPARTMANI TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE WHERE PLUNO = 0),0) > 1
BEGIN
	SET @ERRORMESSAGE = 'HATA : PLU NUMARASI SIFIR OLAN ÜRÜNLER MEVCUT.!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

CREATE TABLE #TMPREYON(PLUNO INT, REYONADI VARCHAR(20))

IF LEN(@DATA) <= 80
	INSERT INTO #TMPREYON(PLUNO, REYONADI)
	SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN WITH (NOLOCK)
	GROUP BY PLUNO, REYONADI

BEGIN TRAN

	IF @ISDEGISEN = 1
	BEGIN
		BEGIN TRY
			DELETE FROM TBL_STOK_MAIN
			WHERE PLUNO IN (SELECT PLUNO FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH

		BEGIN TRY
			DELETE FROM TBL_STOK_KOD
			WHERE BARKOD IN (SELECT BARKOD FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK KOD TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH
	END
	ELSE
	BEGIN
		TRUNCATE TABLE TBL_STOK_MAIN
		TRUNCATE TABLE TBL_STOK_KOD
	END

	BEGIN TRY
		INSERT INTO TBL_STOK_MAIN(PLUNO, BARKOD, STOKADI, DEPARTMAN, KDV, BIRIM, FIYAT, FIYAT2, FIYAT3, TARTILI, CREATEDATE, CREATEUSERCODE, DOVIZKODU, ALISDEPARTMAN, ALISKDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT T.PLUNO, T.BARKOD, T.STOKADI, T.DEPARTMAN, D.KDV, T.BIRIM, T.FIYAT, CASE WHEN ISNULL(T.FIYAT2,0) = 0 THEN T.FIYAT ELSE T.FIYAT2 END, CASE WHEN ISNULL(T.FIYAT3,0) = 0 THEN T.FIYAT ELSE T.FIYAT3 END, T.TARTILI, GETDATE(), APP_NAME(), DOVIZKODU, T.ALISDEPARTMAN, A.KDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM FROM #TEMPFILE T
			INNER JOIN TBL_DEPARTMAN D WITH (NOLOCK) ON D.DEPARTMAN = T.DEPARTMAN
			INNER JOIN TBL_DEPARTMAN A WITH (NOLOCK) ON A.DEPARTMAN = T.ALISDEPARTMAN
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	BEGIN TRY
		INSERT INTO TBL_STOK_KOD(BARKOD, STOKKODU)
		SELECT BARKOD, STOKKODU FROM #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	IF LEN(@DATA) <= 80
		UPDATE TBL_STOK_MAIN 
		SET REYONADI = R.REYONADI
		FROM TBL_STOK_MAIN S
			INNER JOIN #TMPREYON R ON R.PLUNO = S.PLUNO	
	
	IF ISNULL((SELECT COUNT(*) FROM TBL_STOK_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END
	
DROP TABLE #TEMPFILE
DROP TABLE #TMPREYON

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_FIS_DETAY]
	@ID	INT = NULL,
	@DETAYIDS VARCHAR(MAX) = NULL
AS
	IF @DETAYIDS <> ''
	BEGIN
		SELECT * FROM TBL_FIS_DETAY WITH (NOLOCK)
		WHERE ID IN (SELECT CODE FROM dbo.GETPARAMS(@DETAYIDS))
		ORDER BY ID
		
		RETURN
	END
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

	SELECT D.*, P.DEPARTMANADI,
		CASE WHEN LEN(D.BARKOD) = 7 THEN dbo.CHECKSUMKONTROL(D.BARKOD+dbo.ZL(ROUND(D.MIKTAR*1000,0),5),13) ELSE D.BARKOD END AS TERAZIBARKOD
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
		LEFT JOIN TBL_DEPARTMAN P WITH (NOLOCK) ON P.DEPARTMAN = D.DEPARTMAN
	WHERE D.FISID = @ID
	ORDER BY D.ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_PROMOSYON_URUN_IBM_KONTROL] 
	@CARITIPI		VARCHAR(1),
	@PLUNO			INT,
	@MIKTAR			FLOAT,
	@TUTAR			FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 

	DECLARE @STOKKODU VARCHAR(20)

	SELECT @STOKKODU = STOKKODU FROM TBL_STOK_MAIN WITH (NOLOCK)
	WHERE 
		PLUNO = @PLUNO AND
		ISNULL(ISINDIRIM,1) = 1
	
	SET @STOKKODU = ISNULL(@STOKKODU,'-987654')

	DECLARE @CARIGRUP VARCHAR(20)

	IF ISNULL(@CARIKODU,'') <> ''
		SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
		WHERE CARIKODU = @CARIKODU

	SET @CARIGRUP = ISNULL(@CARIGRUP,'')

	IF @CARITIPI = 'M' SET @CARITIPI = NULL
	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(@MIKTAR * PUAN),
		SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
	WHERE 
		U.STOKKODU = @STOKKODU AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		VREYONADI = '' AND
		CARIGRUP = @CARIGRUP AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) <= 1
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('03','05'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(@MIKTAR * PUAN),
			SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
		WHERE 
			U.STOKKODU = @STOKKODU AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			VREYONADI = '' AND
			CARIGRUP = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) <= 1
	
	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE


GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_PROMOSYON_URUN_IBM_BROWSE]
	@BARKOD		VARCHAR(20) = NULL,
	@STOKADI	VARCHAR(50) = NULL,
	@VBARKOD	VARCHAR(20) = NULL,
	@VSTOKADI	VARCHAR(50) = NULL,
	@VREYONADI	VARCHAR(50) = NULL
AS

SELECT 
	PLUNO,
	STOKKODU,
	STOKADI,
	FIYAT 
INTO #STOK 
FROM TBL_STOK_MAIN 
WHERE ID IN (
				SELECT MAX(ID) FROM TBL_STOK_MAIN WITH (NOLOCK)
				GROUP BY STOKKODU
			) AND
	ISNULL(ISINDIRIM,1) = 1

SELECT 
	CASE 
		WHEN (ISNULL(VPLUNO,0) = 0) AND (ISNULL(RTRIM(LTRIM(VREYONADI)),'') = '')  THEN  'ÜRÜN PROMOSYONU' 
		WHEN (ISNULL(VPLUNO,0) <> 0) THEN  'ÜRÜNE ÜRÜN PROMOSYONU'
		WHEN (ISNULL(RTRIM(LTRIM(VREYONADI)),'') <> '')  THEN  'ÜRÜNE REYON PROMOSYONU'
	ELSE 'ÜRÜN PROMOSYONU' END AS PROMOSYONTIPI,
	CASE WHEN U.CARITIPI = 'H' THEN 'HERKESE' ELSE 'MÜŞTERİYE' END AS MUSTERITIPI,
	S.BARKOD,
	S.STOKADI,
	S.FIYAT,
	AMIKTAR AS MIKTAR,
	U.INDYUZDE,
	U.INDTUTAR,
	V.BARKOD AS VBARKOD,
	V.STOKADI AS VSTOKADI,
	U.VMIKTAR,
	ISNULL(VREYONADI,'') AS VREYONADI,
	U.BITISTARIHI
FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
	INNER JOIN #STOK S WITH (NOLOCK) ON S.STOKKODU = U.STOKKODU
	LEFT JOIN #STOK V WITH (NOLOCK) ON V.STOKKODU = U.VSTOKKODU
WHERE 
	S.BARKOD LIKE ISNULL(@BARKOD+'%', S.BARKOD) AND
	S.STOKADI LIKE	ISNULL(@STOKADI+'%', S.STOKADI)	AND
	ISNULL(V.BARKOD,'')	LIKE ISNULL(@VBARKOD+'%', ISNULL(V.BARKOD,'')) AND
	ISNULL(V.STOKADI,'')  LIKE ISNULL(@VSTOKADI+'%'	,ISNULL(V.STOKADI,''))	AND
	ISNULL(U.VREYONADI,'') LIKE ISNULL(@VREYONADI+'%', 	ISNULL(U.VREYONADI,''))

ORDER BY S.STOKADI

DROP TABLE #STOK

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_PROMOSYON_URUN_BROWSE]
	@BARKOD		VARCHAR(20) = NULL,
	@STOKADI	VARCHAR(50) = NULL,
	@VBARKOD	VARCHAR(20) = NULL,
	@VSTOKADI	VARCHAR(50) = NULL,
	@VREYONADI	VARCHAR(50) = NULL
AS

SELECT 
	PLUNO,
	BARKOD,
	STOKADI,
	FIYAT 
INTO #STOK 
FROM TBL_STOK_MAIN 
WHERE ID IN (
				SELECT MAX(ID) FROM TBL_STOK_MAIN WITH (NOLOCK)
				GROUP BY PLUNO
			) AND
	ISNULL(ISINDIRIM,1) = 1

SELECT 
	CASE 
		WHEN (ISNULL(VPLUNO,0) = 0) AND (ISNULL(RTRIM(LTRIM(VREYONADI)),'') = '')  THEN  'ÜRÜN PROMOSYONU' 
		WHEN (ISNULL(VPLUNO,0) <> 0) THEN  'ÜRÜNE ÜRÜN PROMOSYONU'
		WHEN (ISNULL(RTRIM(LTRIM(VREYONADI)),'') <> '')  THEN  'ÜRÜNE REYON PROMOSYONU'
	ELSE 'ÜRÜN PROMOSYONU' END AS PROMOSYONTIPI,
	CASE WHEN U.CARITIPI = 'H' THEN 'HERKESE' ELSE 'MÜŞTERİYE' END AS MUSTERITIPI,
	S.BARKOD,
	S.STOKADI,
	S.FIYAT,
	AMIKTAR AS MIKTAR,
	U.INDYUZDE,
	U.INDTUTAR,
	V.BARKOD AS VBARKOD,
	V.STOKADI AS VSTOKADI,
	U.VMIKTAR,
	ISNULL(VREYONADI,'') AS VREYONADI,
	U.BITISTARIHI
FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
	INNER JOIN #STOK S WITH (NOLOCK) ON S.PLUNO = U.PLUNO
	LEFT JOIN #STOK V WITH (NOLOCK) ON V.PLUNO = U.VPLUNO
WHERE 
	S.BARKOD LIKE ISNULL(@BARKOD+'%', S.BARKOD) AND
	S.STOKADI LIKE	ISNULL(@STOKADI+'%', S.STOKADI)	AND
	ISNULL(V.BARKOD,'')	LIKE ISNULL(@VBARKOD+'%', ISNULL(V.BARKOD,'')) AND
	ISNULL(V.STOKADI,'')  LIKE ISNULL(@VSTOKADI+'%'	,ISNULL(V.STOKADI,''))	AND
	ISNULL(U.VREYONADI,'') LIKE ISNULL(@VREYONADI+'%', 	ISNULL(U.VREYONADI,''))

ORDER BY S.STOKADI

DROP TABLE #STOK
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_DETAY_LIST]
	@FISID	INT
AS

	SELECT
		D.ID,
		D.FISID,
		D.SATIRNO,
		D.TIP,
		D.PLUNO,
		D.BARKOD,
		D.STOKKODU,
		D.STOKADI,
		D.KDV,
		D.DEPARTMAN,
		D.MIKTAR,
		D.BIRIM,
		D.FIYAT,
		D.TUTAR,
		D.INDYUZDE,
		D.INDTUTAR,
		D.ARTYUZDE,
		D.ARTTUTAR,
		D.KASIYERKODU,
		D.KASIYERADI,
		D.PLASIYERKODU,
		D.PLASIYERADI,
		D.ACIKLAMA,
		D.BARKODTYPE,
		D.DOVIZKODU,
		D.DOVIZKURU,
		D.DOVIZTUTARI,
		D.PUAN,
		D.TEVKIFATKODU,
		D.TEVKIFATACIKLAMA,
		D.TEVKIFATORANI,
		D.OTVKODU,
		D.OTVACIKLAMA,
		D.OTVORANI,
		ISNULL(S.ISINDIRIM,1) AS ISINDIRIM
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
		LEFT JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
	WHERE
		D.FISID = @FISID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_STOK_MAIN_LIST]
	@BARKOD VARCHAR(20) = NULL,
	@PLUNO INT = NULL
AS
	IF @BARKOD IS NOT NULL
		SELECT
			S.ID,
			S.PLUNO,
			S.BARKOD,
			S.STOKKODU,
			S.STOKADI,
			S.DEPARTMAN,
			S.KDV,
			S.BIRIM,
			S.FIYAT,
			S.FIYAT2,
			S.FIYAT3,
			CASE WHEN D.ID IS NULL THEN 'TL' ELSE ISNULL(S.DOVIZKODU,'TL') END AS DOVIZKODU, 
			CASE WHEN ISNULL(D.DOVIZKURU,1) = 0 THEN 1 ELSE ISNULL(D.DOVIZKURU,1) END DOVIZKURU,
			S.TARTILI,
			S.CREATEDATE,
			S.CREATEUSERCODE,
			S.ALISDEPARTMAN,
			S.ALISKDV,
			S.RENK,
			S.BEDEN,
			S.MODELKODU,
			S.TEVKIFATKODU,
			S.TEVKIFATACIKLAMA,
			S.TEVKIFATORANI,
			S.OTVKODU,
			S.OTVACIKLAMA,
			S.OTVORANI,
			S.ISINDIRIM
		FROM TBL_STOK_MAIN S WITH (NOLOCK)
			LEFT JOIN TBL_DOVIZ D WITH (NOLOCK) ON D.DOVIZKODU = S.DOVIZKODU
		WHERE S.BARKOD = @BARKOD
	ELSE
		SELECT
			S.ID,
			S.PLUNO,
			S.BARKOD,
			S.STOKKODU,
			S.STOKADI,
			S.DEPARTMAN,
			S.KDV,
			S.BIRIM,
			S.FIYAT,
			S.FIYAT2,
			S.FIYAT3,
			CASE WHEN D.ID IS NULL THEN 'TL' ELSE ISNULL(S.DOVIZKODU,'TL') END AS DOVIZKODU, 
			CASE WHEN ISNULL(D.DOVIZKURU,1) = 0 THEN 1 ELSE ISNULL(D.DOVIZKURU,1) END DOVIZKURU,
			S.TARTILI,
			S.CREATEDATE,
			S.CREATEUSERCODE,
			S.ALISDEPARTMAN,
			S.ALISKDV,
			S.RENK,
			S.BEDEN,
			S.MODELKODU,
			S.TEVKIFATKODU,
			S.TEVKIFATACIKLAMA,
			S.TEVKIFATORANI,
			S.OTVKODU,
			S.OTVACIKLAMA,
			S.OTVORANI,
			S.ISINDIRIM
		FROM TBL_STOK_MAIN S WITH (NOLOCK)
			LEFT JOIN TBL_DOVIZ D WITH (NOLOCK) ON D.DOVIZKODU = S.DOVIZKODU
		WHERE S.PLUNO = @PLUNO
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_BEKLETME_MAIN_LIST]
	@ID	INT = NULL,
	@ISBEKLETME BIT = NULL,
	@BELGEKODU VARCHAR(20) = NULL
AS

	SELECT
		B.ID,
		B.ISBEKLETME,
		B.KASANO,
		B.BELGEKODU,
		B.TARIH,
		B.TIP,
		B.VERGINO,
		B.CARIKODU,
		B.CARIADI,
		ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
		B.TUTAR,
		B.INDYUZDE,
		B.INDTUTAR,
		B.ARTYUZDE,
		B.ARTTUTAR,
		B.KASIYERKODU,
		B.KASIYERADI,
		B.ISEFATURA,
		B.ALIAS,
		B.YETKILIKODU,
		B.YETKILIADI,
		B.OKCNO,
		ISNULL(C.ISVERESIYE,0) AS ISVERESIYE
	FROM TBL_BEKLETME_MAIN B WITH (NOLOCK)
		LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = B.CARIKODU
	WHERE
		B.ID = ISNULL(@ID, B.ID) AND
		B.ISBEKLETME = ISNULL(@ISBEKLETME, B.ISBEKLETME) AND
		B.BELGEKODU = ISNULL(@BELGEKODU, B.BELGEKODU)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_MAIN_LIST]
	@CARIKODU	VARCHAR(20) = NULL,
	@CARIADI	VARCHAR(50)	= NULL,
	@VERGINO	VARCHAR(20)	= NULL,
	@TELEFON	VARCHAR(20) = NULL,
	@SUBEKODU	VARCHAR(20) = NULL
AS
	SET NOCOUNT ON
	
	CREATE TABLE #TEMPTBL(UNIQUEID INT PRIMARY KEY IDENTITY(1,1), ID INT, CARINO INT, CARIKODU VARCHAR(20), CARIADI VARCHAR(50), ADRES VARCHAR(MAX), 
	LATITUDE VARCHAR(20), LONGITUDE	VARCHAR(20), VERGIDAIRESI VARCHAR(20), VERGINO VARCHAR(20), INDIRIM FLOAT, GRUP VARCHAR(20), 
	CREATEDATE DATETIME, CREATEUSERCODE VARCHAR(100), FIYATTIPNO TINYINT, ISEFATURA BIT, EMAIL VARCHAR(MAX), CARITIPI VARCHAR(1), TELEFON VARCHAR(20), 
	SUBEID INT, SUBEKODU VARCHAR(20), ISVERESIYE BIT)
	
	IF @CARIKODU IS NOT NULL
		INSERT INTO #TEMPTBL(ID, CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, SUBEID, SUBEKODU, ISVERESIYE)
		SELECT
			C.ID,
			C.CARINO,
			C.CARIKODU,
			C.CARIADI,
			C.ADRES,
			C.VERGIDAIRESI,
			C.VERGINO,
			C.INDIRIM,
			C.GRUP,
			C.CREATEDATE,
			C.CREATEUSERCODE,
			C.FIYATTIPNO,
			C.ISEFATURA,
			C.EMAIL,
			C.CARITIPI,
			C.TELEFON,
			ISNULL(S.SUBEID,0) AS SUBEID,
			ISNULL(B.SUBEKODU,'<SECIM YAPILMAMIS>') AS SUBEKODU,
			ISNULL(ISVERESIYE,0) AS ISVERESIYE
		FROM TBL_CARI_MAIN C WITH (NOLOCK)
			LEFT JOIN TBL_SUBE_CARI S WITH (NOLOCK) ON S.CARIKODU = C.CARIKODU
			LEFT JOIN TBL_SUBE B WITH (NOLOCK) ON B.ID = S.SUBEID
		WHERE
			C.CARIKODU = @CARIKODU
	ELSE
	IF @TELEFON IS NOT NULL
	BEGIN
		DECLARE @CKOD VARCHAR(20)
		SELECT TOP 1 @CKOD = CARIKODU FROM TBL_CARI_TELEFON
		WHERE TELEFON LIKE '%'+@TELEFON

		IF @CKOD IS NOT NULL
			INSERT INTO #TEMPTBL(ID, CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, SUBEID, SUBEKODU, ISVERESIYE)
			SELECT
				C.ID,
				C.CARINO,
				C.CARIKODU,
				C.CARIADI,
				C.ADRES,
				C.VERGIDAIRESI,
				C.VERGINO,
				C.INDIRIM,
				C.GRUP,
				C.CREATEDATE,
				C.CREATEUSERCODE,
				C.FIYATTIPNO,
				C.ISEFATURA,
				C.EMAIL,
				C.CARITIPI,
				C.TELEFON,
				ISNULL(S.SUBEID,0) AS SUBEID,
				ISNULL(B.SUBEKODU,'<SECIM YAPILMAMIS>') AS SUBEKODU,
				ISNULL(ISVERESIYE,0) AS ISVERESIYE
			FROM TBL_CARI_MAIN C WITH (NOLOCK)
				LEFT JOIN TBL_SUBE_CARI S WITH (NOLOCK) ON S.CARIKODU = C.CARIKODU
				LEFT JOIN TBL_SUBE B WITH (NOLOCK) ON B.ID = S.SUBEID
			WHERE
				C.CARIKODU = @CKOD
		ELSE
			INSERT INTO #TEMPTBL(ID, CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, SUBEID, SUBEKODU, ISVERESIYE)
			SELECT
				C.ID,
				C.CARINO,
				C.CARIKODU,
				C.CARIADI,
				C.ADRES,
				C.VERGIDAIRESI,
				C.VERGINO,
				C.INDIRIM,
				C.GRUP,
				C.CREATEDATE,
				C.CREATEUSERCODE,
				C.FIYATTIPNO,
				C.ISEFATURA,
				C.EMAIL,
				C.CARITIPI,
				C.TELEFON,
				ISNULL(S.SUBEID,0) AS SUBEID,
				ISNULL(B.SUBEKODU,'<SECIM YAPILMAMIS>') AS SUBEKODU,
				ISNULL(ISVERESIYE,0) AS ISVERESIYE
			FROM TBL_CARI_MAIN C WITH (NOLOCK)
				LEFT JOIN TBL_SUBE_CARI S WITH (NOLOCK) ON S.CARIKODU = C.CARIKODU
				LEFT JOIN TBL_SUBE B WITH (NOLOCK) ON B.ID = S.SUBEID
			WHERE
				C.TELEFON LIKE '%'+@TELEFON
	END
	ELSE IF @VERGINO IS NOT NULL
		INSERT INTO #TEMPTBL(ID, CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, SUBEID, SUBEKODU, ISVERESIYE)
		SELECT
			C.ID,
			C.CARINO,
			C.CARIKODU,
			C.CARIADI,
			C.ADRES,
			C.VERGIDAIRESI,
			C.VERGINO,
			C.INDIRIM,
			C.GRUP,
			C.CREATEDATE,
			C.CREATEUSERCODE,
			C.FIYATTIPNO,
			C.ISEFATURA,
			C.EMAIL,
			C.CARITIPI,
			C.TELEFON,
			ISNULL(S.SUBEID,0) AS SUBEID,
			ISNULL(B.SUBEKODU,'<SECIM YAPILMAMIS>') AS SUBEKODU,
			ISNULL(ISVERESIYE,0) AS ISVERESIYE
		FROM TBL_CARI_MAIN C WITH (NOLOCK)
			LEFT JOIN TBL_SUBE_CARI S WITH (NOLOCK) ON S.CARIKODU = C.CARIKODU
			LEFT JOIN TBL_SUBE B WITH (NOLOCK) ON B.ID = S.SUBEID
		WHERE
			C.VERGINO = @VERGINO
	ELSE
		INSERT INTO #TEMPTBL(ID, CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, SUBEID, SUBEKODU, ISVERESIYE)
		SELECT
			C.ID,
			C.CARINO,
			C.CARIKODU,
			C.CARIADI,
			C.ADRES,
			C.VERGIDAIRESI,
			C.VERGINO,
			C.INDIRIM,
			C.GRUP,
			C.CREATEDATE,
			C.CREATEUSERCODE,
			C.FIYATTIPNO,
			C.ISEFATURA,
			C.EMAIL,
			C.CARITIPI,
			C.TELEFON,
			ISNULL(S.SUBEID,0) AS SUBEID,
			ISNULL(B.SUBEKODU,'<SECIM YAPILMAMIS>') AS SUBEKODU,
			ISNULL(ISVERESIYE,0) AS ISVERESIYE
		FROM TBL_CARI_MAIN C WITH (NOLOCK)
			LEFT JOIN TBL_SUBE_CARI S WITH (NOLOCK) ON S.CARIKODU = C.CARIKODU
			LEFT JOIN TBL_SUBE B WITH (NOLOCK) ON B.ID = S.SUBEID
		WHERE
			C.CARIKODU = ISNULL(@CARIKODU, C.CARIKODU) AND
			C.VERGINO = ISNULL(@VERGINO, C.VERGINO) AND
			C.CARIADI LIKE ISNULL('%'+@CARIADI+'%', C.CARIADI) AND
			C.TELEFON LIKE ISNULL('%'+@TELEFON, C.TELEFON)
	
	UPDATE #TEMPTBL
	SET ADRES = A.ADRES,
		LATITUDE = A.LATITUDE,
		LONGITUDE = A.LONGITUDE
	FROM #TEMPTBL T
		INNER JOIN TBL_CARI_ADRES A WITH (NOLOCK) ON A.CARIKODU = T.CARIKODU AND A.AKTIF = 1

	IF ISNULL(@SUBEKODU,'') <> ''
		SELECT * FROM #TEMPTBL
		WHERE SUBEKODU = @SUBEKODU
		ORDER BY UNIQUEID
	ELSE
		SELECT * FROM #TEMPTBL
		ORDER BY UNIQUEID

	DROP TABLE #TEMPTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_HAREKET_IBM_LOG_LIST]
	@ILKTARIH	SMALLDATETIME = '09/10/2023',
	@SONTARIH	SMALLDATETIME = '09/10/2023',
	@MAGAZANO VARCHAR(6) = '1',
	@TARTIFLAG VARCHAR(MAX) = '2755'
AS
SET @SONTARIH = DATEADD(DAY, 1, @SONTARIH)
DECLARE 
	@FLAG1 VARCHAR(2) = '',
	@FLAG2 VARCHAR(2) = '',
	@FLAG3 VARCHAR(2) = '',
	@ZNO VARCHAR(4) = NULL

SELECT @ZNO = CONVERT(VARCHAR(4),MAX(FISNO)+1) FROM TBL_XZ_LOG
WHERE TIP = 'Z'

SET @ZNO = dbo.ZL(ISNULL(@ZNO, '1'),4)

DECLARE @TBL TABLE (ID INT IDENTITY(1,1), FLAG VARCHAR(MAX))	

EXEC SP_OUTPUT_MESSAGE '1'

INSERT INTO @TBL(FLAG)
SELECT CODE FROM dbo.GETPARAMS(@TARTIFLAG)	

SELECT 
	@FLAG1 = SUBSTRING(CASE WHEN ID = 1 THEN FLAG ELSE @FLAG1 END,1,2),
	@FLAG2 = SUBSTRING(CASE WHEN ID = 2 THEN FLAG ELSE @FLAG2 END,1,2),
	@FLAG3 = SUBSTRING(CASE WHEN ID = 3 THEN FLAG ELSE @FLAG3 END,1,2) 
FROM @TBL

SET DATEFORMAT mdy; 

SET @MAGAZANO = CASE WHEN ISNULL(@MAGAZANO,'0')='0' THEN '1' ELSE @MAGAZANO END
SET @MAGAZANO = dbo.ZL(@MAGAZANO,6)

CREATE TABLE #FISKODTBL(FISID INT PRIMARY KEY, TRANSACTIONNO VARCHAR(20))

INSERT INTO #FISKODTBL(FISID, TRANSACTIONNO)
SELECT F.ID AS FISID, ROW_NUMBER() OVER (PARTITION BY CONVERT(SMALLDATETIME, CONVERT(VARCHAR, TARIH, 112)) ORDER BY ID ASC) AS TRANSACTIONNO
FROM TBL_FIS_MAIN F WITH (NOLOCK)
WHERE
	TARIH >= @ILKTARIH AND
	TARIH < @SONTARIH

CREATE TABLE #HRTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, BELGEID INT, ISIPTAL BIT, SATIRNO INT, DATA VARCHAR(MAX), TIP INT, TUTAR FLOAT, KDVTUTAR FLOAT, DEPARTMAN INT, HRID INT)

EXEC SP_OUTPUT_MESSAGE '1.01'

SELECT 
	FISID, 
	COUNT(D.ID) ADET, 
	SUM((CASE WHEN D.TIP = 'SAT' THEN 1 ELSE -1 END) * ((CASE WHEN (KDV = 0) OR (F.TUTAR+ABS(F.INDTUTAR) = 0) THEN 0 ELSE
	(CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END) - ABS(CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END * (F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END)) -
	(((CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END) - ABS(CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END * (F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END))) / (1+(D.KDV/100.00)))
	END))) AS KDVTUTAR
INTO #FISDETAY FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = D.FISID
GROUP BY FISID

EXEC SP_OUTPUT_MESSAGE '1.02'

SELECT 
	FISID,
	ABS(SUM(D.INDTUTAR)) AS INDTUTAR
INTO #FISIND FROM TBL_FIS_DETAY D WITH (NOLOCK)
GROUP BY FISID
HAVING SUM(MIKTAR) > 0

EXEC SP_OUTPUT_MESSAGE '1.03'

SELECT FISID, COUNT(ID) ADET INTO #FISODEME FROM TBL_FIS_ODEME WITH (NOLOCK) GROUP BY FISID

EXEC SP_OUTPUT_MESSAGE '1.04'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	ID,
	CASE WHEN TIP = 3 THEN 1 ELSE 0 END,
	-1,
	dbo.ZL(K.TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'RH'+
	CASE WHEN TIP = 3 THEN '1' ELSE '0' END+ --IPTAL MI
	'XX'+
	dbo.SR(KASIYERKODU,8)+
	CONVERT(VARCHAR, TARIH, 112)+REPLACE(CONVERT(VARCHAR, TARIH, 108),':','')+
	CONVERT(VARCHAR, TARIH, 112)+REPLACE(CONVERT(VARCHAR, TARIH, 108),':','')+
	dbo.SL(BELGEKODU,10)+
	CONVERT(VARCHAR, CASE WHEN TIP = 3 THEN 0 WHEN TIP = 8 THEN 4 ELSE TIP END)+
	dbo.ZL('TPLM',4)+--TOPLAM SATIR SAYISI GELECEK
	dbo.ZL(CONVERT(VARCHAR, CAST(TUTAR AS MONEY),0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(D.KDVTUTAR AS MONEY),0),15)+
	dbo.SR(CASE WHEN CARIKODU <> '' THEN CARIKODU WHEN VERGINO <> '' THEN VERGINO ELSE '11111111111' END,24)+
	CASE WHEN (F.INDTUTAR <> 0) OR (I.INDTUTAR <> 0) THEN '1' ELSE '0' END+ --TOPLAM INDIRIMI VAR MI 
	'0'+--TAXFREE VAR MI 
	'1'+ --EXTRA SATIRI VAR MI 
	@ZNO+
	'00XXXX', --KULLANILMIYOR
	0
FROM TBL_FIS_MAIN F WITH (NOLOCK)
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
	INNER JOIN 	#FISDETAY D ON D.FISID = F.ID
	LEFT JOIN 	#FISIND I ON I.FISID = F.ID
	LEFT JOIN 	#FISODEME O ON O.FISID = F.ID


EXEC SP_OUTPUT_MESSAGE '2'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	ID,
	CASE WHEN TIP = 3 THEN 1 ELSE 0 END,
	0,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'TD'+
	CASE WHEN TIP = 3 THEN '1' ELSE '0' END+ --IPTAL MI
	'XX'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(F.INDTUTAR) AS MONEY),0),15)+
	'000000000000.00'+
	'000000000000.00'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(F.INDTUTAR) AS MONEY),0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(D.INDTUTAR) AS MONEY),0),15)+
	'000000000000.00'+
	'0'+
	'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
	1
FROM TBL_FIS_MAIN F WITH (NOLOCK)
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
	INNER JOIN 	(
					SELECT 
						FISID,
						SUM(CASE WHEN TIP = 'SAT' THEN ABS(D.INDTUTAR) ELSE -1*ABS(D.DOVIZTUTARI - D.TUTAR) END) AS INDTUTAR
					FROM TBL_FIS_DETAY D WITH (NOLOCK)
					GROUP BY FISID
					HAVING SUM(MIKTAR) > 0
				) D ON D.FISID = F.ID
WHERE
	F.ID IN (SELECT BELGEID FROM #HRTABLE) AND
	(
		(F.INDTUTAR <> 0) OR
		(D.INDTUTAR <> 0)
	)

EXEC SP_OUTPUT_MESSAGE '3'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	ID,
	CASE WHEN TIP = 3 THEN 1 ELSE 0 END,
	1,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'RE'+
	CASE WHEN TIP = 3 THEN '1' ELSE '0' END+ --IPTAL MI
	'XX                        003059                                        XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
	2
FROM TBL_FIS_MAIN F WITH (NOLOCK)
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
WHERE
	F.ID IN (SELECT BELGEID FROM #HRTABLE) 


EXEC SP_OUTPUT_MESSAGE '4'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP, TUTAR, KDVTUTAR, DEPARTMAN, HRID)
SELECT
	D.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	SATIRNO,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'IS'+
	CASE WHEN D.TIP = 'SAT' THEN '0' ELSE '1' END+
	'XX'+
	'0000'+--PLASIYERKODU
	dbo.ZL(CONVERT(VARCHAR, DEPARTMAN),2)+
	dbo.ZL(CONVERT(VARCHAR, KDV),2)+
	dbo.ZL(
		CONVERT(VARCHAR, ABS(ROUND(
								CASE WHEN 
									BARKOD <> '' AND 
									SUBSTRING(BARKOD,1,2) = @FLAG1 OR   
									SUBSTRING(BARKOD,1,2) = @FLAG2 OR   
									SUBSTRING(BARKOD,1,2) = @FLAG3 
								THEN CONVERT(FLOAT,MIKTAR * 1000)
								ELSE CONVERT(FLOAT,MIKTAR) END,0)
				)),6)+
	CASE WHEN 
		BARKOD <> '' AND 
		SUBSTRING(BARKOD,1,2) = @FLAG1 OR   
		SUBSTRING(BARKOD,1,2) = @FLAG2 OR   
		SUBSTRING(BARKOD,1,2) = @FLAG3 
	THEN '1'
	ELSE '0' END+--GRAMAJLI MI 
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CASE WHEN D.TIP = 'SAT' THEN FIYAT ELSE (ABS(D.DOVIZTUTARI) / CASE WHEN MIKTAR = 0 THEN 1 ELSE MIKTAR END) END) AS MONEY),0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CONVERT(FLOAT, CASE WHEN D.TIP = 'SAT' THEN D.TUTAR ELSE ABS(D.DOVIZTUTARI) END)) AS MONEY),0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CONVERT(FLOAT, (CASE WHEN (KDV = 0) OR (F.TUTAR+ABS(F.INDTUTAR) = 0) THEN 0 ELSE ROUND((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END) * (D.TUTAR + D.INDTUTAR))) - ((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END) * (D.TUTAR + D.INDTUTAR))) / (1+(D.KDV/100.00))),2) END))) AS MONEY),0),15)+
	'0'+--SATIŞ ŞEKLİ
	dbo.SR(BARKOD,24)+
	'000000000000.00'+--DÖVİZ BİRİM FİYATI
	'00000'+
	CASE WHEN (D.INDTUTAR <> 0) OR (F.INDTUTAR <> 0) THEN '1' ELSE '0' END+
	'0'+
	'020XXXXXXXX',
	3,
	
	(CASE WHEN D.TIP = 'SAT' THEN 1 ELSE -1 END) * ((CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END) - ABS((CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END * (F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END)))),
	(CASE WHEN D.TIP = 'SAT' THEN 1 ELSE -1 END) * ((CASE WHEN (KDV = 0) OR (F.TUTAR+ABS(F.INDTUTAR) = 0) THEN 0 ELSE
	(CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END) - ABS(CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END * (F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END)) -
	(((CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END) - ABS(CASE WHEN D.TIP = 'SAT' THEN (D.TUTAR - ABS(D.INDTUTAR)) ELSE (ABS(D.TUTAR)) END * (F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END))) / (1+(D.KDV/100.00)))
	END)),
	DEPARTMAN,
	D.ID
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = D.FISID
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE)	

EXEC SP_OUTPUT_MESSAGE '5'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	D.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	SATIRNO,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'ID'+
	CASE WHEN D.TIP = 'SAT' THEN '0' ELSE '1' END+
	'XX'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CONVERT(FLOAT, CASE WHEN D.TIP = 'SAT' THEN D.INDTUTAR ELSE ABS(D.DOVIZTUTARI) - ABS(D.TUTAR) END)) AS MONEY), 0),15)+
	'000000000000.00'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CONVERT(FLOAT, CASE WHEN D.TIP = 'SAT' THEN D.INDTUTAR ELSE ABS(D.DOVIZTUTARI) - ABS(D.TUTAR) END)) AS MONEY), 0),15)+
	'000000000000.00'+
	'000000000000.00'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CONVERT(FLOAT, CASE WHEN D.TIP = 'SAT' THEN ABS((F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END) * (D.TUTAR - ABS(D.INDTUTAR))) ELSE ABS((F.INDTUTAR / CASE WHEN (F.TUTAR+ABS(F.INDTUTAR)) = 0 THEN 1 ELSE (F.TUTAR+ABS(F.INDTUTAR)) END) * ABS(D.TUTAR))END)) AS MONEY), 0),15)+
	'000000000000.00'+
	'0'+
	'XXXXXXXXXXXX',
	4
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = D.FISID
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE)	AND (((D.INDTUTAR <> 0) OR (D.TIP = 'IPT' AND ABS(D.DOVIZTUTARI) <> ABS(D.TUTAR))) OR (F.INDTUTAR <> 0))

EXEC SP_OUTPUT_MESSAGE '6'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP, HRID)
SELECT
	D.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	SATIRNO,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'IN'+
	CASE WHEN D.TIP = 'SAT' THEN '0' ELSE '1' END+
	'XX'+
	'0'+
	'000002'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CONVERT(FLOAT, CASE WHEN D.TIP = 'SAT' THEN D.INDTUTAR ELSE ABS(D.DOVIZTUTARI) - ABS(D.TUTAR) END)) AS MONEY), 0),15)+
	'                        '+
	dbo.SR(CASE WHEN ISNULL(D.STOKKODU,'') = '' THEN D.BARKOD ELSE D.STOKKODU END,24)+
	dbo.ZL('INDS',4)+
	'                                        XXXX',
	5,
	D.ID
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = D.FISID
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = D.FISID
WHERE D.INDTUTAR <> 0 OR (D.TIP = 'IPT' AND ABS(D.DOVIZTUTARI) <> ABS(D.TUTAR)) 

EXEC SP_OUTPUT_MESSAGE '7'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	O.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	ROW_NUMBER() OVER(PARTITION BY O.FISID ORDER BY O.ID ASC) + H.MAXSATIRNO,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'PY'+
	'0'+
	'XX'+
	dbo.ZL(CONVERT(VARCHAR, O.KREDINO),2)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(CONVERT(FLOAT, O.TUTAR)) AS MONEY), 0),15)+
	'0'+
	'000000000000.00'+
	'                        '+
	'00'+
	'00                                        99XXXXXXXXXX0XXXX',
	6
FROM TBL_FIS_ODEME O WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = O.FISID
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = O.FISID

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	F.ID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	ROW_NUMBER() OVER(PARTITION BY F.ID ORDER BY F.ID ASC) + H.MAXSATIRNO,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'RN'+
	'0'+
	'XX'+
	'0'+
	'004002'+
		dbo.ZL(CONVERT(VARCHAR, CAST(ABS(F.INDTUTAR) AS MONEY), 0),15)+
	'                                                0000                                        XXXX',
	7
FROM TBL_FIS_MAIN F WITH (NOLOCK) 
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = F.ID

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	F.ID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	ROW_NUMBER() OVER(PARTITION BY F.ID ORDER BY F.ID ASC) + H.MAXSATIRNO,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'RN'+
	'0'+
	'XX'+
	'1'+
	'002017'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(0) AS MONEY), 0),15)+
	dbo.SR(CASE WHEN CARIKODU <> '' THEN CARIKODU WHEN VERGINO <> '' THEN VERGINO ELSE '11111111111' END,24)+
	dbo.SR(CASE WHEN CARIKODU <> '' THEN CARIKODU WHEN VERGINO <> '' THEN VERGINO ELSE '11111111111' END,24)+
	'0000'+
	CONVERT(VARCHAR, TARIH,112)+
	@MAGAZANO+
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	dbo.ZL(TRANSACTIONNO,6)+
	REPLACE(CONVERT(VARCHAR, TARIH, 108),':','')+
	'           XXXX',
	7
FROM TBL_FIS_MAIN F WITH (NOLOCK) 
	INNER JOIN #FISKODTBL K ON K.FISID = F.ID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = F.ID

EXEC SP_OUTPUT_MESSAGE '9'

CREATE TABLE #KDVTABLE(
						FISID INT, 
						SATIS0 FLOAT,
						SATIS1 FLOAT, SATIS2 FLOAT, SATIS3 FLOAT, SATIS4 FLOAT, SATIS5 FLOAT, 
						SATIS6 FLOAT, SATIS7 FLOAT, SATIS8 FLOAT, SATIS9 FLOAT, SATIS10 FLOAT, 
						KDV0 FLOAT,
						KDV1 FLOAT, KDV2 FLOAT, KDV3 FLOAT, KDV4 FLOAT, KDV5 FLOAT, 
						KDV6 FLOAT, KDV7 FLOAT, KDV8 FLOAT, KDV9 FLOAT, KDV10 FLOAT 
					  )

INSERT INTO #KDVTABLE(FISID, SATIS0, KDV0, SATIS1, KDV1, SATIS2, KDV2, SATIS3, KDV3, SATIS4, KDV4, SATIS5, KDV5, SATIS6, KDV6, SATIS7, KDV7, SATIS8, KDV8, SATIS9, KDV9, SATIS10, KDV10)
SELECT BELGEID, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 FROM #HRTABLE
GROUP BY BELGEID

SELECT 
	BELGEID,
	DEPARTMAN,
	SUM(TUTAR) AS TUTAR,
	SUM(KDVTUTAR) AS KDVTUTAR
INTO #DEPARTMAN FROM #HRTABLE
WHERE TIP = 3
GROUP BY BELGEID, DEPARTMAN

UPDATE #KDVTABLE SET SATIS0 = D.TUTAR, KDV0 = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN  = 0
UPDATE #KDVTABLE SET SATIS1 = D.TUTAR, KDV1 = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN  = 1
UPDATE #KDVTABLE SET SATIS2 = D.TUTAR, KDV2 = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN  = 2
UPDATE #KDVTABLE SET SATIS3 = D.TUTAR, KDV3  = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 3 
UPDATE #KDVTABLE SET SATIS4 = D.TUTAR, KDV4  = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 4 
UPDATE #KDVTABLE SET SATIS5 = D.TUTAR, KDV5  = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 5 
UPDATE #KDVTABLE SET SATIS6 = D.TUTAR, KDV6  = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 6 
UPDATE #KDVTABLE SET SATIS7 = D.TUTAR, KDV7  = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 7 
UPDATE #KDVTABLE SET SATIS8 = D.TUTAR, KDV8  = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 8 
UPDATE #KDVTABLE SET SATIS9 = D.TUTAR, KDV9  = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 9 
UPDATE #KDVTABLE SET SATIS10 = D.TUTAR,KDV10 = D.KDVTUTAR FROM #KDVTABLE K INNER JOIN #DEPARTMAN AS D ON D.BELGEID = K.FISID WHERE DEPARTMAN = 10

EXEC SP_OUTPUT_MESSAGE '10'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	K.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	H.MAXSATIRNO+1,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'VF'+
	'0'+
	'XX'+
	'0'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.KDV0) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.KDV1) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.KDV2) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.KDV3) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.KDV4) AS MONEY), 0),15)+
	'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
	8
FROM #KDVTABLE K WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = K.FISID
	INNER JOIN #FISKODTBL L ON L.FISID = F.ID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = K.FISID

EXEC SP_OUTPUT_MESSAGE '11'

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	K.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	H.MAXSATIRNO+1,
	dbo.ZL(TRANSACTIONNO,6)+
	'STNO'+ --SATIR NO
	dbo.ZL(CONVERT(VARCHAR, KASANO),3)+
	@MAGAZANO+
	'DF'+
	'0'+
	'XX'+
	'0'+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.SATIS0) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.SATIS1) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.SATIS2) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.SATIS3) AS MONEY), 0),15)+
	dbo.ZL(CONVERT(VARCHAR, CAST(ABS(K.SATIS4) AS MONEY), 0),15)+
	'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
	9
FROM #KDVTABLE K WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = K.FISID
	INNER JOIN #FISKODTBL L ON L.FISID = F.ID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = K.FISID

EXEC SP_OUTPUT_MESSAGE '12'

UPDATE #HRTABLE 
SET DATA = REPLACE(DATA, 'TPLM', dbo.ZL(CONVERT(VARCHAR, SATIRADEDI),4))
FROM #HRTABLE H
	INNER JOIN (
					SELECT BELGEID, COUNT(*) SATIRADEDI
					FROM #HRTABLE
					GROUP BY BELGEID
			  ) AS D ON D.BELGEID = H.BELGEID
WHERE SATIRNO = -1

EXEC SP_OUTPUT_MESSAGE '13'

UPDATE #HRTABLE
SET SATIRNO = D.SATNO,
	DATA = REPLACE(H.DATA, 'STNO', dbo.ZL(D.SATNO,4))
FROM #HRTABLE H
	INNER JOIN (
					SELECT ROW_NUMBER() OVER(PARTITION BY BELGEID ORDER BY BELGEID, SATIRNO, TIP) - 1  AS SATNO, ID FROM #HRTABLE
			   ) AS D ON  D.ID = H.ID

EXEC SP_OUTPUT_MESSAGE '14'

UPDATE #HRTABLE
SET DATA = REPLACE(H.DATA, 'INDS', dbo.ZL(CONVERT(VARCHAR, D.SATIRNO),4))
FROM #HRTABLE H
	INNER JOIN (SELECT * FROM #HRTABLE WHERE TIP = 3) D ON D.HRID = H.HRID
WHERE H.HRID IS NOT NULL AND H.TIP = 5

EXEC SP_OUTPUT_MESSAGE '15'

SELECT DATA FROM #HRTABLE
ORDER BY BELGEID, SATIRNO

EXEC SP_OUTPUT_MESSAGE '16'

DROP TABLE #KDVTABLE
DROP TABLE #HRTABLE
DROP TABLE #DEPARTMAN
DROP TABLE #FISDETAY
DROP TABLE #FISIND
DROP TABLE #FISODEME
DROP TABLE #FISKODTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_FIS_MAIN_LIST]
	@ID		INT = NULL,
	@FISBARKOD VARCHAR(20) = NULL,
	@ILKTARIH	SMALLDATETIME = NULL,
	@SONTARIH	SMALLDATETIME = NULL,
	@ISSEND		BIT = NULL,
	@ISHARICI	BIT = NULL
AS
	CREATE TABLE #RETTABLE(
		ID INT, KASANO INT, BELGEKODU VARCHAR(20), TARIH DATETIME, TIP TINYINT, VERGINO VARCHAR(20), CARIKODU VARCHAR(20), CARIADI VARCHAR(50), TUTAR FLOAT, 
		INDYUZDE FLOAT, INDTUTAR FLOAT, ARTYUZDE FLOAT, ARTTUTAR FLOAT, KASIYERKODU VARCHAR(4), KASIYERADI VARCHAR(50), PARAUSTU FLOAT, ISEFATURA BIT, FIYATTIPNO INT, 
		EFATURAKODU VARCHAR(20), UUID VARCHAR(50), TYPE VARCHAR(20), ALIAS VARCHAR(200), YETKILIKODU VARCHAR(4), YETKILIADI VARCHAR(50)
	)

	IF @ID IS NOT NULL
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
 		WHERE F.ID = @ID
	ELSE IF @FISBARKOD IS NOT NULL
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE SUBSTRING(CONVERT(VARCHAR, F.TARIH, 112)+REPLACE(CONVERT(VARCHAR, F.TARIH, 114),':',''),1,14) = SUBSTRING(@FISBARKOD,1,14)
	ELSE IF ISNULL(@ISSEND,1) = 0
	BEGIN
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE 
			((ISSEND IS NULL OR ISSEND = 0) OR (@ISHARICI = 1)) AND
			CONVERT(VARCHAR, F.TARIH, 112) >= CONVERT(VARCHAR, @ILKTARIH, 112) AND
			CONVERT(VARCHAR, F.TARIH, 112) <= CONVERT(VARCHAR, @SONTARIH, 112) 
	END
	ELSE
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE 
			CONVERT(VARCHAR, F.TARIH, 112) >= CONVERT(VARCHAR, @ILKTARIH, 112) AND
			CONVERT(VARCHAR, F.TARIH, 112) <= CONVERT(VARCHAR, @SONTARIH, 112) 
		
	UPDATE #RETTABLE
	SET TYPE = E.TYPE
	FROM #RETTABLE R
		INNER JOIN TBL_CARI_EFATURA E WITH (NOLOCK) ON E.ALIAS = R.ALIAS
	WHERE R.ISEFATURA = 1

	SELECT * FROM #RETTABLE
	ORDER BY ID ASC

	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_KDV_LIST]
	@FISID	INT
AS
	SELECT *
	FROM TBL_FIS_KDV WITH (NOLOCK)
	WHERE
		FISID = @FISID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_FIS_KDV_INSERT]
	@FISID			INT,
	@KDV			FLOAT,
	@KDVTUTAR		FLOAT,
	@KDVHARICTUTAR	FLOAT,
	@TUTAR			FLOAT
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_KDV(FISID, KDV, KDVTUTAR, KDVHARICTUTAR, TUTAR)
	SELECT @FISID, @KDV, @KDVTUTAR, @KDVHARICTUTAR, @TUTAR
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_AYLIK_MALI_REPORT_EN]
	@KASANO		INT = 1,
	@ILKTARIH	DATETIME = '01/01/2000',
	@SONTARIH	DATETIME = '01/01/2018'
AS

DECLARE @TARIH DATETIME, @KUMULATIFTUTAR FLOAT, @KUMULATIFKDV FLOAT

SET @TARIH = ISNULL(@TARIH, GETDATE()-365)


IF @ILKTARIH IS NULL
	SET @ILKTARIH = @TARIH
IF @SONTARIH IS NULL
	SET @SONTARIH = GETDATE()

SELECT @KUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@KUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1) AND M.KASANO = @KASANO AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH

SET @KUMULATIFKDV = ISNULL(@KUMULATIFKDV,0)
SET @KUMULATIFTUTAR = ISNULL(@KUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'E-ARSIV DETAILS', 0, 99

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'RETURN DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CANCEL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 3
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOTAL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN(0,1,2)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMENT DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'DEP'+CONVERT(VARCHAR, DEPARTMAN)+' (%'+CONVERT(VARCHAR, KDV)+' TAX)' AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2)
GROUP BY DEPARTMAN, KDV
ORDER BY DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAX DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' TAX',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),10)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PAYMENT DETAILS (SALES)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - PAYMENT TOTAL',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PAYMENT DETAILS (RETURN)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+CASE WHEN D.KREDITIPI='NAKİT' THEN 'CASH' ELSE D.KREDITIPI END

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - TOTAL PAYMENT',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'OTHER DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'CANCEL LINES TOTAL',
	SUM(ABS(TUTAR)) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'DISCOUNTS TOTAL',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1)
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @KASANO AND ISEFATURA = 0 AND TARIH >= @ILKTARIH AND TARIH <= @SONTARIH AND TIP IN (0,1)
	) AS H

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

TRUNCATE TABLE #DETAYTBL

INSERT INTO #DETAYTBL
SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'E-FATURA DETAILS', 0, 99

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'RETURN DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CANCEL TOTAL', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 3
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOTAL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN(0,1,2)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEP. TOTAL DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'DEP'+CONVERT(VARCHAR, DEPARTMAN)+' (%'+CONVERT(VARCHAR, KDV)+' TAX)' AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2)
GROUP BY DEPARTMAN, KDV
ORDER BY DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAX DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' TAX',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),10)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PAYMENTS TOTAL (SALES)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - PAYMENTS TOTAL',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PAYMENTS TOTAL (RETURN)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - PAYMENTS TOTAL',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'OTHER DETAILS', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'CANCEL LINES TOTAL',
	SUM(ABS(TUTAR)) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'DISCOUNTS TOTAL',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1)
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @KASANO AND ISEFATURA = 1 AND TARIH >= @ILKTARIH AND TARIH <= @SONTARIH AND TIP IN (0,1)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'E-ARŞİV + E-FATURA TOTAL', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAX TOTAL', @KUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOTAL', @KUMULATIFTUTAR, 4

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @ILKTARIH AS ILKTARIH, @SONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_STOK_MAIN_BROWSE]
	@RECORDCOUNT	INT		= NULL,
	@BARKOD		VARCHAR(20)	= NULL,
	@STOKADI	VARCHAR(50)	= NULL,
	@PLUNO		INT			= NULL,
	@DEPARTMAN	INT			= NULL,
	@KDV		FLOAT		= NULL,
	@FIYAT		FLOAT		= NULL,
	@BIRIM		VARCHAR(10)	= NULL,
	@TARTILI	VARCHAR(1)	= NULL,
	@RENK		VARCHAR(50)	= NULL,
	@BEDEN		VARCHAR(20)	= NULL,
	@MODELKODU	VARCHAR(20)	= NULL,
	@REYONADI	VARCHAR(20)	= NULL,
	@OZELKOD1	VARCHAR(50)	= NULL,
	@OZELKOD2	VARCHAR(50)	= NULL,
	@OZELKOD3	VARCHAR(50)	= NULL,
	@OZELKOD4	VARCHAR(50)	= NULL,
	@OZELKOD5	VARCHAR(50)	= NULL,
	@OZELKOD6	VARCHAR(50)	= NULL,
	@OZELKOD7	VARCHAR(50)	= NULL,
	@OZELKOD8	VARCHAR(50)	= NULL,
	@OZELKOD9	VARCHAR(50)	= NULL,
	@OZELKOD10	VARCHAR(50)	= NULL
AS
	SET NOCOUNT ON;

	SET @RECORDCOUNT = ISNULL(@RECORDCOUNT, 1000000)
	
	SELECT
		TOP (@RECORDCOUNT)
		S.ID,
		S.MODELKODU,
		S.BARKOD,
		S.STOKADI,
		S.PLUNO,
		S.DEPARTMAN,
		S.KDV,
		S.BIRIM,
		S.FIYAT,
		S.FIYAT2,
		S.FIYAT3,
		S.TARTILI,
		S.RENK,
		S.BEDEN,
		S.CREATEDATE,
		S.CREATEUSERCODE,
		S.REYONADI,
		ISNULL(O.OZELKOD1,'') AS OZELKOD1,
		ISNULL(O.OZELKOD2,'') AS OZELKOD2,
		ISNULL(O.OZELKOD3,'') AS OZELKOD3,
		ISNULL(O.OZELKOD4,'') AS OZELKOD4,
		ISNULL(O.OZELKOD5,'') AS OZELKOD5,
		ISNULL(O.OZELKOD6,'') AS OZELKOD6,
		ISNULL(O.OZELKOD7,'') AS OZELKOD7,
		ISNULL(O.OZELKOD8,'') AS OZELKOD8,
		ISNULL(O.OZELKOD9,'') AS OZELKOD9,
		ISNULL(O.OZELKOD10,'') AS OZELKOD10,
		ISNULL(L.LIMIT,0) AS LIMIT
	FROM TBL_STOK_MAIN S WITH (NOLOCK)
		LEFT JOIN TBL_STOK_OZEL_KOD O  WITH (NOLOCK) ON O.BARKOD = S.BARKOD
		LEFT JOIN TBL_PROMOSYON_LIMIT L WITH (NOLOCK) ON L.PLUNO = S.PLUNO
	WHERE
		S.BARKOD	LIKE ISNULL(@BARKOD,				S.BARKOD)	AND
		S.STOKADI	LIKE ISNULL('%'+@STOKADI+'%',	S.STOKADI)	AND
		S.PLUNO		= ISNULL(@PLUNO,				S.PLUNO)	AND
		S.DEPARTMAN	= ISNULL(@DEPARTMAN,			S.DEPARTMAN)AND
		S.KDV			= ISNULL(@KDV,				S.KDV)		AND
		S.FIYAT		= ISNULL(@FIYAT,				S.FIYAT)	AND
		S.BIRIM	LIKE  ISNULL('%'+@BIRIM+'%',		S.BIRIM)	AND
		S.TARTILI		= ISNULL(@TARTILI,			S.TARTILI)	AND
		S.RENK	LIKE  ISNULL(@RENK+'%',				S.RENK)		AND
		S.BEDEN	LIKE  ISNULL(@BEDEN+'%',			S.BEDEN)	AND
		S.MODELKODU LIKE  ISNULL(@MODELKODU+'%',	S.MODELKODU)AND
		S.REYONADI LIKE  ISNULL('%'+@REYONADI+'%',	S.REYONADI) AND
		ISNULL(O.OZELKOD1,'') LIKE  ISNULL('%'+@OZELKOD1+'%',ISNULL(O.OZELKOD1,'')) AND
		ISNULL(O.OZELKOD2,'') LIKE  ISNULL('%'+@OZELKOD2+'%',ISNULL(O.OZELKOD2,'')) AND
		ISNULL(O.OZELKOD3,'') LIKE  ISNULL('%'+@OZELKOD3+'%',ISNULL(O.OZELKOD3,'')) AND
		ISNULL(O.OZELKOD4,'') LIKE  ISNULL('%'+@OZELKOD4+'%',ISNULL(O.OZELKOD4,'')) AND
		ISNULL(O.OZELKOD5,'') LIKE  ISNULL('%'+@OZELKOD5+'%',ISNULL(O.OZELKOD5,'')) AND
		ISNULL(O.OZELKOD6,'') LIKE  ISNULL('%'+@OZELKOD6+'%',ISNULL(O.OZELKOD6,'')) AND
		ISNULL(O.OZELKOD7,'') LIKE  ISNULL('%'+@OZELKOD7+'%',ISNULL(O.OZELKOD7,'')) AND
		ISNULL(O.OZELKOD8,'') LIKE  ISNULL('%'+@OZELKOD8+'%',ISNULL(O.OZELKOD8,'')) AND
		ISNULL(O.OZELKOD9,'') LIKE  ISNULL('%'+@OZELKOD9+'%',ISNULL(O.OZELKOD9,'')) AND
		ISNULL(O.OZELKOD10,'')LIKE  ISNULL('%'+@OZELKOD10+'%',ISNULL(O.OZELKOD10,'')) 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_IMPORT_FILE]
	@FILENAME	NVARCHAR(500),
	@FILETYPE	INT
AS
	SET NOCOUNT ON

	DECLARE
		@DURUM		TINYINT,
		@ACIKLAMA	VARCHAR(MAX),
		@ISERROR	BIT	,
		@DOSYAADI	VARCHAR(MAX)

	TRUNCATE TABLE TBL_IMPORT_FILE

	BEGIN TRY
		DECLARE @sql NVARCHAR(4000) = 'BULK INSERT TBL_IMPORT_FILE FROM ''' + @FILENAME + ''' WITH (ROWTERMINATOR = ''0x0A'', CODEPAGE = ''1254'')';
		EXEC(@sql);
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN (BULK INSERT) HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		IF @FILETYPE = 107
			EXEC SP_IMPORT_URUN_FILE 0
		ELSE
		IF @FILETYPE = 1071
			EXEC SP_IMPORT_URUN_FILE 1
		ELSE
		IF @FILETYPE = 108
			EXEC SP_IMPORT_CARI_FILE 0
		ELSE
		IF @FILETYPE = 1081
			EXEC SP_IMPORT_CARI_FILE 1
		ELSE
		IF @FILETYPE = 109
			EXEC SP_IMPORT_KASIYER_FILE
		ELSE
		IF @FILETYPE = 110
			EXEC SP_IMPORT_DOVIZ_FILE
		ELSE
		IF @FILETYPE = 126
			EXEC SP_IMPORT_REYON_FILE
		ELSE
		IF @FILETYPE = 113
			EXEC SP_IMPORT_PROMOSYON_FILE
		ELSE
		IF @FILETYPE = 138
			EXEC SP_IMPORT_OZELKOD_FILE
		ELSE
		IF @FILETYPE = 907
			EXEC SP_IMPORT_URUN_IBM_FILE
		ELSE
		IF @FILETYPE = 908
			EXEC SP_IMPORT_CARI_IBM_FILE
		ELSE
		IF @FILETYPE = 909
			EXEC SP_IMPORT_PROMOSYON_IBM_FILE
		ELSE
		IF @FILETYPE = 999
			EXEC SP_IMPORT_EFATURA_FILE
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_IMPORT_OZELKOD_FILE]
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRY
	SELECT
		RTRIM(SUBSTRING(DATA,1,20)) AS BARKOD,
		RTRIM(SUBSTRING(DATA,21,50)) AS OZELKOD1,
		RTRIM(SUBSTRING(DATA,71,50)) AS OZELKOD2,
		RTRIM(SUBSTRING(DATA,121,50)) AS OZELKOD3,
		RTRIM(SUBSTRING(DATA,171,50)) AS OZELKOD4,
		RTRIM(SUBSTRING(DATA,221,50)) AS OZELKOD5,
		RTRIM(SUBSTRING(DATA,271,50)) AS OZELKOD6,
		RTRIM(SUBSTRING(DATA,321,50)) AS OZELKOD7,
		RTRIM(SUBSTRING(DATA,371,50)) AS OZELKOD8,
		RTRIM(SUBSTRING(DATA,421,50)) AS OZELKOD9,
		RTRIM(SUBSTRING(DATA,471,50)) AS OZELKOD10
	INTO #TEMPFILE FROM TBL_IMPORT_FILE
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : ÖZEL KOD DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

BEGIN TRAN
	TRUNCATE TABLE TBL_STOK_OZEL_KOD
	
	BEGIN TRY
		INSERT INTO TBL_STOK_OZEL_KOD
		SELECT * FROM #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_OZEL_KOD TABLOSUNA OZEL KOD INSERT EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

DROP TABLE #TEMPFILE

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_YETKI_TIP_LIST] 
	@TIP		VARCHAR(1) = NULL,
	@YETKIKODU	VARCHAR(20) = NULL
AS

SELECT
	T.ID,
	T.YETKIID,
	A.YETKIKODU,
	A.YETKIADI,
	T.AKTIF,
	ISNULL(T.MOBIL,0) AS MOBIL
FROM TBL_YETKI_TIP T WITH (NOLOCK)
	INNER JOIN TBL_YETKI_TANIM A WITH (NOLOCK) ON A.ID = T.YETKIID
WHERE
	TIP = ISNULL(@TIP, TIP) AND
	YETKIKODU = ISNULL(@YETKIKODU, YETKIKODU)
ORDER BY T.ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_YETKI_TIP_UPDATE]
	@ID INT,
	@AKTIF BIT,
	@MOBIL BIT
AS
	UPDATE TBL_YETKI_TIP
	SET AKTIF = @AKTIF,
		MOBIL = @MOBIL
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_PROMOSYON_LIMIT_KONTROL] 
	@CARITIPI		VARCHAR(1) = 'H',
	@DEFAULTFIYATTIPI TINYINT = 1
AS
	IF NOT EXISTS(SELECT TOP 1 ID FROM TBL_PROMOSYON_LIMIT WITH (NOLOCK))
	BEGIN
		SELECT @DEFAULTFIYATTIPI AS FIYATTIPI
		RETURN
	END

	DECLARE @FIYATTIPI INT
	SET @FIYATTIPI = @DEFAULTFIYATTIPI
	
	SET DATEFORMAT mdy; 

	DECLARE @CARIGRUP VARCHAR(20)

	IF @CARITIPI = 'M' SET @CARITIPI = NULL
	
	SELECT PLUNO, SUM(D.MIKTAR) AS MIKTAR, CONVERT(FLOAT, 0) AS LIMIT, CONVERT(TINYINT, @DEFAULTFIYATTIPI) AS FIYATTIPI INTO #STOK FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
	GROUP BY PLUNO
	HAVING SUM(MIKTAR) > 0

	UPDATE #STOK
	SET LIMIT = L.LIMIT,
		FIYATTIPI = L.FIYATTIPI
	FROM #STOK S
		INNER JOIN TBL_PROMOSYON_LIMIT L WITH (NOLOCK) ON L.PLUNO = S.PLUNO
	WHERE 
		L.BASLANGICTARIHI <= GETDATE() AND
		L.BITISTARIHI >= GETDATE() AND
		L.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) 
	
	SELECT TOP 1 @FIYATTIPI = MAX(FIYATTIPI)
	FROM #STOK
	WHERE MIKTAR >= LIMIT AND LIMIT > 0
	IF ISNULL(@FIYATTIPI,0) = 0 SET @FIYATTIPI = @DEFAULTFIYATTIPI
	
	DROP TABLE #STOK

	SELECT @FIYATTIPI AS FIYATTIPI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_DEPARTMAN_INSERT_UPDATE]
	@ID	INT = NULL,
	@DEPARTMAN	TINYINT,
	@KDV		FLOAT,
	@DEPARTMANADI VARCHAR(50) = NULL
AS

	IF @ID IS NULL
		INSERT INTO TBL_DEPARTMAN(DEPARTMAN, KDV, DEPARTMANADI)
		SELECT @DEPARTMAN, @KDV, @DEPARTMANADI
	ELSE
		UPDATE TBL_DEPARTMAN
		SET KDV = @KDV,
			DEPARTMAN = @DEPARTMAN,
			DEPARTMANADI = @DEPARTMANADI
		WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_FIS_MAIN]
	@ID	INT = NULL,
	@GONDERENVKN VARCHAR(20) = NULL
AS
	SET @GONDERENVKN = ISNULL(@GONDERENVKN, '11111111111')

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

	DECLARE 
		@DETAYID INT, @PLUNO INT, @TIP VARCHAR(3), @MIKTAR FLOAT, @TUTAR FLOAT,
		@IPTPLUNO INT, @IPTMIKTAR FLOAT, @IPTTUTAR FLOAT, @ARATOPLAMIND FLOAT, @ARATOPLAMART FLOAT, @INDORAN FLOAT, @ARTORAN FLOAT

	SELECT 
		@ARATOPLAMIND = ABS(INDTUTAR),
		@ARATOPLAMART = ARTTUTAR 
	FROM TBL_FIS_MAIN
	WHERE ID = @ID

	SELECT * INTO #DETAY 
	FROM TBL_FIS_DETAY
	WHERE FISID = @ID
	ORDER BY ID DESC

	DECLARE CURRD CURSOR FAST_FORWARD FOR
	SELECT ID, PLUNO, TIP, ABS(MIKTAR), ABS(TUTAR) FROM #DETAY 
	ORDER BY ID DESC
	OPEN CURRD

	FETCH NEXT FROM CURRD
	INTO @DETAYID, @PLUNO, @TIP, @MIKTAR, @TUTAR 

	SET @IPTPLUNO = 0

	WHILE @@FETCH_STATUS = 0  
	BEGIN
		IF @TIP = 'IPT'
		BEGIN
			SET @IPTPLUNO = @PLUNO		
			SET @IPTMIKTAR = @MIKTAR
			SET @IPTTUTAR = @TUTAR
		END		
		ELSE IF (@IPTPLUNO > 0) AND (@IPTPLUNO = @PLUNO)
		BEGIN
			UPDATE #DETAY
			SET MIKTAR = MIKTAR - @IPTMIKTAR, 
				TUTAR = TUTAR - @IPTTUTAR
			WHERE ID = @DETAYID
			
			SET @IPTPLUNO = 0
		END
		
		FETCH NEXT FROM CURRD
		INTO @DETAYID, @PLUNO, @TIP, @MIKTAR, @TUTAR 
	END

	CLOSE CURRD
	DEALLOCATE CURRD

	SELECT 
		@INDORAN = CASE WHEN SUM(TUTAR) -  SUM(ABS(INDTUTAR)) - SUM(ARTTUTAR) = 0 THEN 0 ELSE @ARATOPLAMIND / (SUM(TUTAR) -  SUM(ABS(INDTUTAR)) + SUM(ARTTUTAR)) END,
		@ARTORAN = CASE WHEN SUM(TUTAR) -  SUM(ABS(INDTUTAR)) - SUM(ARTTUTAR) = 0 THEN 0 ELSE @ARATOPLAMART / (SUM(TUTAR) -  SUM(ABS(INDTUTAR)) + SUM(ARTTUTAR)) END
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0

	UPDATE #DETAY
	SET INDTUTAR = -1 * ((ABS(INDTUTAR) + (@INDORAN * (TUTAR - ABS(INDTUTAR) + ARTTUTAR)))),
		ARTTUTAR = ((ABS(ARTTUTAR) + (@ARTORAN * (TUTAR - ABS(INDTUTAR) + ARTTUTAR)))),
		INDYUZDE = 0,
		ARTYUZDE = 0 
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0

	SELECT 
			@ARATOPLAMIND = SUM(INDTUTAR), 
			@ARATOPLAMART = SUM(ARTTUTAR)
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0


	DECLARE 
		@GRAMAJLIBARKODLAR VARCHAR(MAX)
	
	SET @GRAMAJLIBARKODLAR = NULL
	
	SELECT
		@GRAMAJLIBARKODLAR = 
						COALESCE(
								@GRAMAJLIBARKODLAR + CHAR(13)+dbo.CHECKSUMKONTROL(D.BARKOD+dbo.ZL(ROUND(MIKTAR*1000,0),5),13),
								dbo.CHECKSUMKONTROL(D.BARKOD+dbo.ZL(ROUND(MIKTAR*1000,0),5),13)
								)	
	FROM #DETAY D
			INNER JOIN TBL_STOK_MAIN M WITH (NOLOCK) ON M.BARKOD = D.BARKOD
	WHERE M.TARTILI = 'E'
	
	DROP TABLE #DETAY
	

	DECLARE
		@ARATOPIND FLOAT,
		@FISTUTAR FLOAT

	SELECT @FISTUTAR = TUTAR + ABS(INDTUTAR) - ARTTUTAR, @ARATOPIND = ABS(INDTUTAR) FROM TBL_FIS_MAIN WHERE ID = @ID

	SELECT KDV, SUM((TUTAR - ABS(INDTUTAR) + ARTTUTAR)) AS TUTAR
	INTO #KDVTBL FROM TBL_FIS_DETAY WITH (NOLOCK)
	WHERE FISID = @ID AND (TIP IN ('SAT', 'IPT'))
	GROUP BY KDV

	DELETE FROM #KDVTBL WHERE TUTAR = 0

	SELECT KDV, TUTAR - CASE WHEN @FISTUTAR = 0 THEN 0 ELSE ((TUTAR / @FISTUTAR) * @ARATOPIND) END  AS NETTUTAR INTO #RETTABLE
	FROM #KDVTBL

	DECLARE @KDVHARICTOPLAM FLOAT

	SELECT
		@ID AS FISID,
		KDV,
		ROUND(SUM((NETTUTAR / (1 + (KDV / 100.00)))),2) AS KDVMATRAHI,
		ROUND(SUM((NETTUTAR - (NETTUTAR / (1 + (KDV / 100.00))))),2) AS KDVTUTARI,
		ROUND(SUM(NETTUTAR),2) AS TUTAR
	INTO #KDVTOP FROM #RETTABLE WITH (NOLOCK)
	GROUP BY KDV
	
	SELECT @KDVHARICTOPLAM = SUM(KDVMATRAHI) FROM #KDVTOP
	
	SET @KDVHARICTOPLAM = ISNULL(@KDVHARICTOPLAM,0)

	DECLARE @KDVJSON VARCHAR(MAX)
	SELECT 
	  @KDVJSON = STUFF((
		SELECT 
			', "kdvmatrah('+CONVERT(VARCHAR, KDV)+')":"' + CONVERT(VARCHAR, KDVMATRAHI) +'"'+
			', "hesaplanankdv('+CONVERT(VARCHAR, KDV)+')":"' + CONVERT(VARCHAR, KDVTUTARI) +'"'
		FROM #KDVTOP 
		WHERE (FISID = Results.FISID) 
		FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
	  ,1,2,'') 
	FROM #KDVTOP Results
	GROUP BY FISID
	
	SELECT 
		F.*, 
		CONVERT(VARCHAR, F.TARIH, 112)+SUBSTRING(REPLACE(CONVERT(VARCHAR, F.TARIH, 114),':',''),1,6)+dbo.ZL(KASANO,3) AS FISBARKOD,
		ISNULL(ABS(@ARATOPLAMIND), 0) AS TOPLAMINDTUTARI, ISNULL(@ARATOPLAMART, 0) AS TOPLAMARTTUTARI,
		C.VERGIDAIRESI,
		C.ADRES ,
		C.TELEFON,
		ABS(ISNULL((SELECT SUM(INDTUTAR) FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE FISID = F.ID AND PROMOSYONTIPI = 0),0)) AS TICKETTUTAR,
		ISNULL((SELECT COUNT(*) FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE FISID = F.ID AND ISTICKET = 1),0) AS ISTICKET,
		ISNULL(
				(SELECT SUM(D.TUTAR) FROM TBL_FIS_DETAY D WITH (NOLOCK) 
					INNER JOIN TBL_STOK_MAIN M ON M.BARKOD = D.BARKOD
				WHERE D.FISID = F.ID AND M.REYONADI = 'CEK'
 				),0) AS INDIRIMREYONTUTARI,
		@GRAMAJLIBARKODLAR AS GRAMAJLIBARKOD,
		'{"vkntckn":"'+ISNULL(@GONDERENVKN,'')+
		'","avkntckn":"'+CASE WHEN ISNULL(F.VERGINO,'') = '' THEN '11111111111' ELSE F.VERGINO END+
		'","senaryo":"'+CASE WHEN F.ISEFATURA = 1 THEN 'TEMELFATURA' ELSE 'EARSIVFATURA' END +
		'","tip":"SATIS'+
		'","tarih":"'+REPLACE(CONVERT(VARCHAR, F.TARIH, 102),'.','-') +
		'","no":"'+EFATURAKODU+
		'","ettn":"'+UUID+
		'","parabirimi":"TRY'+
		'","malhizmettoplam":"'+CONVERT(VARCHAR, @KDVHARICTOPLAM)+
		'",'+@KDVJSON+ 
		',"vergidahil":"'+CONVERT(VARCHAR, F.TUTAR)+
		'","odenecek":"'+CONVERT(VARCHAR, F.TUTAR)+'"}' AS EFATURAQRKOD
	FROM TBL_FIS_MAIN F WITH (NOLOCK)
		LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		
	WHERE F.ID = @ID

	DROP TABLE #KDVTBL
	DROP TABLE #RETTABLE
	DROP TABLE #KDVTOP
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KAR_HESAPLA] 
	@PROMOSYONTUTARI FLOAT = 0
AS
	DECLARE @FISID INT, @KARORANI FLOAT, @KARTUTARI FLOAT
	
	SELECT TOP 1 @FISID = ID FROM TBL_BEKLETME_MAIN WITH (NOLOCK) WHERE ISBEKLETME = 0 ORDER BY ID DESC

	SELECT 
		@KARORANI = 
			ROUND(CASE WHEN SUM((ALISFIYAT * MIKTAR)) = 0 THEN 0 ELSE
			(((SUM(D.TUTAR + D.INDTUTAR) - (@PROMOSYONTUTARI)) - SUM(ALISFIYAT * MIKTAR)) / SUM(ALISFIYAT * MIKTAR)) * 100
			END,3),
		@KARTUTARI = ((SUM(D.TUTAR + D.INDTUTAR) - (@PROMOSYONTUTARI)) - SUM(ALISFIYAT * MIKTAR))
	FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
	WHERE FISID = @FISID

	SELECT ISNULL(@KARORANI,0) AS KARORANI, ISNULL(@KARTUTARI,0) AS KARTUTARI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_EFATURA_UPDATE]
AS
	SET NOCOUNT ON
	
	EXEC SP_OUTPUT_MESSAGE '1'

	SELECT * INTO #MUKTBL FROM (
					SELECT MAX(ID) AS ID FROM TBL_CARI_EFATURA_TEMP
					GROUP BY IDENTIFIER, ALIAS
					HAVING COUNT(ID) = 1
					UNION ALL
					SELECT MAX(ID) AS ID FROM TBL_CARI_EFATURA_TEMP
					GROUP BY IDENTIFIER, ALIAS
					HAVING COUNT(ID) > 1
				  ) AS H

	create clustered index idx1 on #MUKTBL (ID)

	SELECT *, CONVERT(INT, 0) AS EFATURAID INTO #TEMPHAREKET FROM TBL_CARI_EFATURA_TEMP WITH (NOLOCK)
	WHERE ID IN (SELECT ID FROM #MUKTBL)

	create clustered index idx2 on #TEMPHAREKET (IDENTIFIER, ALIAS)

	EXEC SP_OUTPUT_MESSAGE '2'
	
	UPDATE #TEMPHAREKET
	SET EFATURAID = F.ID
	FROM #TEMPHAREKET T
		INNER JOIN TBL_CARI_EFATURA F WITH (NOLOCK) ON F.IDENTIFIER = T.IDENTIFIER AND F.ALIAS = T.ALIAS

	EXEC SP_OUTPUT_MESSAGE '3'
	
	UPDATE TBL_CARI_EFATURA
	SET 
		CREATEDATE	= T.CREATEDATE,
		IDENTIFIER	= T.IDENTIFIER,
		AKTIF		= T.AKTIF,
		TITLE		= T.TITLE,
		TYPE		= T.TYPE,
		UPDATEDATE	= T.UPDATEDATE
	FROM TBL_CARI_EFATURA C WITH (NOLOCK)
		INNER JOIN #TEMPHAREKET T ON T.EFATURAID = C.ID
	
	EXEC SP_OUTPUT_MESSAGE '4'

	INSERT INTO TBL_CARI_EFATURA(ALIAS, CREATEDATE, IDENTIFIER, AKTIF, TITLE, TYPE, UPDATEDATE)
	SELECT ALIAS, CREATEDATE, IDENTIFIER, AKTIF, TITLE, TYPE, UPDATEDATE
	FROM #TEMPHAREKET WITH (NOLOCK)
	WHERE EFATURAID = 0

	EXEC SP_OUTPUT_MESSAGE '5'

	DROP TABLE #TEMPHAREKET
	DROP TABLE #MUKTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_CARI_EFATURA_TEMP_INSERT]
	@ALIAS		VARCHAR(MAX), 
	@CREATEDATE	DATETIME, 
	@IDENTIFIER	VARCHAR(MAX), 
	@AKTIF		BIT, 
	@TITLE		VARCHAR(MAX), 
	@TYPE		VARCHAR(MAX), 
	@UPDATEDATE	DATETIME = NULL
AS
		
	INSERT INTO TBL_CARI_EFATURA_TEMP(ALIAS, CREATEDATE, IDENTIFIER, AKTIF, TITLE, TYPE, UPDATEDATE)
	SELECT @ALIAS, @CREATEDATE, @IDENTIFIER, @AKTIF, @TITLE, @TYPE, ISNULL(@UPDATEDATE, @CREATEDATE)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_MAIN_BROWSE]
	@RECORDCOUNT INT = NULL,
	@BELGEKODU	VARCHAR(20) = NULL,
	@TIPADI		VARCHAR(3) = NULL,
	@TARIH		DATETIME = NULL,
	@CARIADI	VARCHAR(50) = NULL,
	@TUTAR		FLOAT = NULL
AS
	DECLARE 
		@ILKTARIH DATETIME,
		@SONTARIH DATETIME
	IF @TARIH IS NOT NULL
	BEGIN
		IF CONVERT(VARCHAR, @TARIH, 108) = '00:00:00'
		BEGIN
			SET @ILKTARIH = @TARIH
			SET @SONTARIH = @TARIH+1
		END
		ELSE
		BEGIN
			SET @ILKTARIH = @TARIH
			SET @SONTARIH = @TARIH
		END
	END
	ELSE
	BEGIN
		SET @ILKTARIH = GETDATE()-365
		SET @SONTARIH = GETDATE()+365
	END
	
	IF ISNULL(@RECORDCOUNT,0) > 0
		SELECT
			TOP (@RECORDCOUNT)
			F.ID,
			F.BELGEKODU,
			F.TIP,
			CONVERT(BIT, CASE WHEN ISNULL(EFATURAKODU, '') <> '' THEN 1 ELSE 0 END) AS ISEARSIV,
			CASE F.TIP WHEN 0 THEN 'FIS' WHEN 1 THEN 'FAT' WHEN 2 THEN 'IAD' WHEN 8 THEN 'IRS' ELSE '' END AS TIPADI,
			F.TARIH,
			F.CARIADI,
			F.TUTAR
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
		WHERE
			F.TIP IN (0,1,2,8) AND
			F.TARIH >= @ILKTARIH AND
			F.TARIH <= @SONTARIH AND
			F.BELGEKODU LIKE ISNULL('%'+@BELGEKODU+'%', F.BELGEKODU) AND
			CASE F.TIP WHEN 0 THEN 'FIS' WHEN 1 THEN 'FAT' WHEN 2 THEN 'IAD' WHEN 8 THEN 'IRS' ELSE '' END LIKE ISNULL('%'+@TIPADI+'%', CASE F.TIP WHEN 0 THEN 'FIS' WHEN 1 THEN 'FAT' WHEN 2 THEN 'IAD' WHEN 8 THEN 'IRS' ELSE '' END) AND
			F.CARIADI LIKE ISNULL('%'+@CARIADI+'%', F.CARIADI) AND
			F.TUTAR = ISNULL(@TUTAR, F.TUTAR)
		ORDER BY TARIH DESC
	ELSE
		SELECT
			F.ID,
			F.BELGEKODU,
			F.TIP,
			CONVERT(BIT, CASE WHEN ISNULL(EFATURAKODU, '') <> '' THEN 1 ELSE 0 END) AS ISEARSIV,
			CASE F.TIP WHEN 0 THEN 'FIS' WHEN 1 THEN 'FAT' WHEN 2 THEN 'IAD' WHEN 8 THEN 'IRS' ELSE '' END AS TIPADI,
			F.TARIH,
			F.CARIADI,
			F.TUTAR
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
		WHERE
			F.TIP IN (0,1,2,8) AND
			F.TARIH >= @ILKTARIH AND
			F.TARIH <= @SONTARIH AND
			F.BELGEKODU LIKE ISNULL('%'+@BELGEKODU+'%', F.BELGEKODU) AND
			CASE F.TIP WHEN 0 THEN 'FIS' WHEN 1 THEN 'FAT' WHEN 2 THEN 'IAD' WHEN 8 THEN 'IRS' ELSE '' END LIKE ISNULL('%'+@TIPADI+'%', CASE F.TIP WHEN 0 THEN 'FIS' WHEN 1 THEN 'FAT' WHEN 2 THEN 'IAD' WHEN 8 THEN 'IRS' ELSE '' END) AND
			F.CARIADI LIKE ISNULL('%'+@CARIADI+'%', F.CARIADI) AND
			F.TUTAR = ISNULL(@TUTAR, F.TUTAR)
		ORDER BY TARIH DESC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_MIKTAR_KONTROL]
	@FISID INT
AS
	SELECT PLUNO, STOKADI, SUM(CONVERT(DECIMAL(21,6),MIKTAR)) FROM TBL_FIS_DETAY WITH (NOLOCK)
	WHERE FISID = @FISID
	GROUP BY PLUNO, STOKADI
	HAVING SUM(CONVERT(DECIMAL(21,6),MIKTAR)) < 0
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_AYLIK_MALI_REPORT]
	@KASANO		INT = 1,
	@ILKTARIH	DATETIME = '01/01/2000',
	@SONTARIH	DATETIME = '01/01/2018'
AS

DECLARE @TARIH DATETIME, @KUMULATIFTUTAR FLOAT, @KUMULATIFKDV FLOAT

SET @TARIH = ISNULL(@TARIH, GETDATE()-365)


IF @ILKTARIH IS NULL
	SET @ILKTARIH = @TARIH
IF @SONTARIH IS NULL
	SET @SONTARIH = GETDATE()

SELECT @KUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@KUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1) AND M.KASANO = @KASANO AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH

SET @KUMULATIFKDV = ISNULL(@KUMULATIFKDV,0)
SET @KUMULATIFTUTAR = ISNULL(@KUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'E-ARSIV DÖKÜMÜ', 0, 99

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 3
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN(0,1,2)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KSM'+CONVERT(VARCHAR, DEPARTMAN)+' (%'+CONVERT(VARCHAR, KDV)+' KDV)' AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2)
GROUP BY DEPARTMAN, KDV
ORDER BY DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),10)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAHSİLAT DÖKÜMÜ (SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - TAHSİLAT TOPLAMI',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME DÖKÜMÜ (İADE)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - ÖDEME TOPLAMI',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 0 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1)
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @KASANO AND ISEFATURA = 0 AND TARIH >= @ILKTARIH AND TARIH <= @SONTARIH AND TIP IN (0,1)
	) AS H

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

TRUNCATE TABLE #DETAYTBL

INSERT INTO #DETAYTBL
SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'E-FATURA DÖKÜMÜ', 0, 99

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 3
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN(0,1,2)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KSM'+CONVERT(VARCHAR, DEPARTMAN)+' (%'+CONVERT(VARCHAR, KDV)+' KDV)' AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2)
GROUP BY DEPARTMAN, KDV
ORDER BY DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),10)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAHSİLAT DÖKÜMÜ (SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - TAHSİLAT TOPLAMI',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(0,1)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME DÖKÜMÜ (İADE)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - ÖDEME TOPLAMI',
	SUM(
		ABS(D.TUTAR)
		) AS TUTAR,
	4
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @KASANO AND ISEFATURA = 1 AND M.TARIH >= @ILKTARIH AND M.TARIH <= @SONTARIH AND TIP IN(2)

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1)
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @KASANO AND ISEFATURA = 1 AND TARIH >= @ILKTARIH AND TARIH <= @SONTARIH AND TIP IN (0,1)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'E-ARŞİV + E-FATURA TOPLAMI', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV TOPLAMI', @KUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'GENEL TOPLAM', @KUMULATIFTUTAR, 4

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @ILKTARIH AS ILKTARIH, @SONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_INDEX_REPAIR]
AS
DECLARE @Database VARCHAR(255)
DECLARE @Table VARCHAR(255)
DECLARE @cmd NVARCHAR(500)
DECLARE @fillfactor INT

SET @fillfactor = 90

DECLARE DatabaseCursor CURSOR FOR
SELECT name FROM MASTER.dbo.sysdatabases
WHERE name = 'BARPOS'
ORDER BY 1

OPEN DatabaseCursor

FETCH NEXT FROM DatabaseCursor INTO @Database
WHILE @@FETCH_STATUS = 0
BEGIN

SET @cmd = 'DECLARE TableCursor CURSOR FOR SELECT ''['' + table_catalog + ''].['' + table_schema + ''].['' +
table_name + '']'' as tableName FROM ' + @Database + '.INFORMATION_SCHEMA.TABLES
WHERE table_type = ''BASE TABLE'''

--create table cursor
EXEC (@cmd)
OPEN TableCursor

FETCH NEXT FROM TableCursor INTO @Table
WHILE @@FETCH_STATUS = 0
BEGIN

IF (@@MICROSOFTVERSION / POWER(2, 24) >= 9)
BEGIN
--SQL 2005 veya sonrası
SET @cmd = 'ALTER INDEX ALL ON ' + @Table + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@cmd)
END
ELSE
BEGIN
--SQL 2000
DBCC DBREINDEX(@Table,' ',@fillfactor)
END

FETCH NEXT FROM TableCursor INTO @Table
END

CLOSE TableCursor
DEALLOCATE TableCursor

FETCH NEXT FROM DatabaseCursor INTO @Database
END
CLOSE DatabaseCursor
DEALLOCATE DatabaseCursor
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_URUN_IBM_FILE]
AS
SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX),
	@MAXPLU INT

CREATE TABLE #TMPFILE(ID INT IDENTITY(1,1) PRIMARY KEY, DATA VARCHAR(MAX))
INSERT INTO #TMPFILE(DATA)
SELECT DATA FROM TBL_IMPORT_FILE

CREATE TABLE #STOKTBL(
						ID INT IDENTITY(1,1),
						PLUNO INT,
						DURUM	  TINYINT, --0 Yeni Kayıt, 1 Değiştir, 2 Sil
						STOKKODU VARCHAR(20),
						STOKADI VARCHAR(50), 
						FIYAT FLOAT, 
						DEPARTMAN INT,
						BIRIM VARCHAR(4),
						TARTILI VARCHAR(1),
						FIYAT2 FLOAT,
						FIYAT3 FLOAT,
						REYONADI VARCHAR(20),
						BARKODID INT,
						AKTIF BIT
					)
					
CREATE TABLE #BARKODTBL(ID INT IDENTITY(1,1), DURUM TINYINT, STOKKODU VARCHAR(20), BARKOD VARCHAR(20), BARKODID INT)

CREATE INDEX IDX_STOKKODU_BARKODTBL ON #BARKODTBL (STOKKODU);
CREATE INDEX IDX_STOKKODU_STOKTBL ON #STOKTBL (STOKKODU);

BEGIN TRY

EXEC SP_OUTPUT_MESSAGE '1'

	INSERT INTO #STOKTBL(DURUM, STOKKODU, STOKADI, FIYAT, FIYAT2, FIYAT3, DEPARTMAN, BIRIM, TARTILI, REYONADI, BARKODID, AKTIF)
	SELECT
		CONVERT(TINYINT, SUBSTRING(DATA,5,1)) AS DURUM,
		RTRIM(SUBSTRING(DATA,6,24)) AS STOKKODU,
		RTRIM(SUBSTRING(DATA,54,40)) AS STOKADI,
		CASE WHEN CHARINDEX(',', SUBSTRING(DATA,356,15)) > 0
			THEN CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,356,15),',','.'))
			ELSE CONVERT(FLOAT, SUBSTRING(DATA,356,15)) END AS FIYAT,
		CASE WHEN CHARINDEX(',', SUBSTRING(DATA,371,15)) > 0
			THEN CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,371,15),',','.'))
			ELSE CONVERT(FLOAT, SUBSTRING(DATA,371,15)) END AS FIYAT2,
		CASE WHEN CHARINDEX(',', SUBSTRING(DATA,386,15)) > 0
			THEN CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,386,15),',','.'))
			ELSE CONVERT(FLOAT, SUBSTRING(DATA,386,15)) END AS FIYAT3,
		CONVERT(INT, SUBSTRING(DATA,532,3)) AS DEPARTMAN,
		CASE CONVERT(INT, SUBSTRING(DATA,283,1)) 
			WHEN 0 THEN 'ADET'
			WHEN 1 THEN 'KG'
			WHEN 2 THEN 'MT'
			WHEN 3 THEN 'LT'
			WHEN 4 THEN 'M2'
			WHEN 5 THEN 'M3'
		ELSE 'ADET' END AS BIRIM,
		CASE CONVERT(INT, SUBSTRING(DATA,687,1)) 
			WHEN 0 THEN 'H'
			WHEN 1 THEN 'E'
			WHEN 2 THEN 'A'
		ELSE 'H' END AS TARTILI,			
		RTRIM(SUBSTRING(DATA,198,8)) AS REYONADI,
		ID+1,
		CASE WHEN SUBSTRING(DATA,587,1) = '1' THEN 0 ELSE 1 END AS AKTIF 
	FROM #TMPFILE
	WHERE DATA LIKE '01%'
	ORDER BY ID ASC
	

EXEC SP_OUTPUT_MESSAGE '2'

	INSERT INTO #BARKODTBL(DURUM, STOKKODU, BARKOD, BARKODID)
	SELECT
		CONVERT(TINYINT, SUBSTRING(DATA,5,1)) AS DURUM,
		RTRIM(SUBSTRING(DATA,6,24)) AS STOKKODU,
		RTRIM(SUBSTRING(DATA,30,24)) AS BARKOD,
		ID
	FROM #TMPFILE
	WHERE DATA LIKE '02%' AND 
	(
		LEN(RTRIM(SUBSTRING(DATA,6,24))) <= 20 AND
		LEN(RTRIM(SUBSTRING(DATA,30,24))) <= 20 
	)
	ORDER BY ID ASC

	DELETE FROM #BARKODTBL
	WHERE ID NOT IN (
						SELECT MAX(ID) FROM #BARKODTBL
						GROUP BY BARKOD
					)

	EXEC SP_OUTPUT_MESSAGE '3'

END TRY
BEGIN CATCH
	DROP TABLE #STOKTBL
	DROP TABLE #BARKODTBL
	SET @ERRORMESSAGE = 'HATA : ÜRÜN DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH



DECLARE @DEPARTMAN INT

SELECT TOP 1 @DEPARTMAN = DEPARTMAN
FROM #STOKTBL
WHERE DEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	DROP TABLE #STOKTBL
	DROP TABLE #BARKODTBL
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU DEPARTMAN TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

DECLARE 
	@KODS VARCHAR(MAX) 
	
SELECT 
	@KODS =  COALESCE( @KODS + ',' + BARKOD , BARKOD)
FROM #BARKODTBL WITH (NOLOCK)
GROUP BY BARKOD
HAVING COUNT(*) > 1

IF ISNULL(@KODS,'') <> ''
BEGIN
	DROP TABLE #STOKTBL
	DROP TABLE #BARKODTBL
	SET @ERRORMESSAGE = 'HATA : MÜKERRER BARKODLAR > '+@KODS
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

SELECT @MAXPLU = MAX(PLUNO) FROM TBL_STOK_MAIN WITH (NOLOCK)
SET @MAXPLU = ISNULL(@MAXPLU,0) + 1

EXEC SP_OUTPUT_MESSAGE '4'

SELECT 
	S.ID,
	S.PLUNO,
	CASE WHEN B.DURUM = 2 THEN B.DURUM WHEN S.DURUM = 2 THEN S.DURUM ELSE 1 END AS DURUM,
	B.BARKOD, 
	S.STOKKODU, 
	S.STOKADI, 
	S.FIYAT, 
	S.FIYAT2, 
	S.FIYAT3, 
	S.DEPARTMAN, 
	S.BIRIM, 
	S.TARTILI, 
	S.REYONADI,
	S.AKTIF
INTO #TEMPTBL FROM #STOKTBL S 
	INNER JOIN #BARKODTBL B ON B.STOKKODU = S.STOKKODU

UPDATE #TEMPTBL
SET PLUNO = ID + @MAXPLU

CREATE CLUSTERED INDEX IDX_BARKOD_TEMPTBL ON #TEMPTBL (BARKOD);

--ALTER TABLE #TEMPTBL ADD ID INT IDENTITY(1,1), KDV INT
ALTER TABLE #TEMPTBL ADD KDV INT

UPDATE #TEMPTBL 
SET KDV = D.KDV
FROM #TEMPTBL T 
	INNER JOIN TBL_DEPARTMAN D WITH (NOLOCK) ON D.DEPARTMAN = T.DEPARTMAN

EXEC SP_OUTPUT_MESSAGE '5'

IF ISNULL((SELECT COUNT(*) FROM #TEMPTBL),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : URUN DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

BEGIN TRAN
	BEGIN TRY
		DELETE FROM TBL_STOK_MAIN
		WHERE BARKOD IN (SELECT BARKOD FROM #TEMPTBL WHERE DURUM = 2 OR AKTIF = 0)
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPTBL
		DROP TABLE #STOKTBL
		DROP TABLE #BARKODTBL
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : STOK MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

EXEC SP_OUTPUT_MESSAGE '7'

	BEGIN TRY
		UPDATE TBL_STOK_MAIN
		SET 
			STOKKODU = T.STOKKODU,
			STOKADI = T.STOKADI, 
			DEPARTMAN = T.DEPARTMAN, 
			KDV = T.KDV, 
			BIRIM = T.BIRIM, 
			FIYAT = T.FIYAT, 
			FIYAT2 = T.FIYAT2, 
			FIYAT3 = T.FIYAT3, 
			TARTILI = T.TARTILI, 
			CREATEDATE = GETDATE(), 
			CREATEUSERCODE = APP_NAME(), 
			ALISDEPARTMAN = T.DEPARTMAN, 
			ALISKDV = T.KDV, 
			REYONADI = T.REYONADI 		
		FROM TBL_STOK_MAIN S WITH (NOLOCK)
			INNER JOIN #TEMPTBL T ON T.BARKOD = S.BARKOD
		WHERE AKTIF = 1
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPTBL
		DROP TABLE #STOKTBL
		DROP TABLE #BARKODTBL
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

EXEC SP_OUTPUT_MESSAGE '8'


	BEGIN TRY
		INSERT INTO TBL_STOK_MAIN(PLUNO,STOKKODU, BARKOD, STOKADI, DEPARTMAN, KDV, BIRIM, FIYAT, FIYAT2, FIYAT3, TARTILI, CREATEDATE, CREATEUSERCODE, DOVIZKODU, ALISDEPARTMAN, ALISKDV, REYONADI, RENK, BEDEN, MODELKODU)
		SELECT PLUNO, T.STOKKODU, T.BARKOD, T.STOKADI, T.DEPARTMAN, D.KDV, T.BIRIM, T.FIYAT, T.FIYAT2, T.FIYAT3, T.TARTILI, GETDATE(), APP_NAME(), 'TL', T.DEPARTMAN, D.KDV, REYONADI, '', '', '' FROM #TEMPTBL T
			INNER JOIN TBL_DEPARTMAN D WITH (NOLOCK) ON D.DEPARTMAN = T.DEPARTMAN
		WHERE AKTIF = 1 AND BARKOD NOT IN (SELECT BARKOD FROM TBL_STOK_MAIN WITH (NOLOCK))
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPTBL
		DROP TABLE #STOKTBL
		DROP TABLE #BARKODTBL
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	

	IF ISNULL((SELECT COUNT(*) FROM TBL_STOK_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPTBL
		DROP TABLE #STOKTBL
		DROP TABLE #BARKODTBL
		DROP TABLE #TMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END

EXEC SP_OUTPUT_MESSAGE '9'

DROP TABLE #TEMPTBL
DROP TABLE #STOKTBL
DROP TABLE #BARKODTBL
DROP TABLE #TMPFILE

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_HEDEF_IBM_KONTROL] 
	@CARITIPI		VARCHAR(1) ,
	@ARATOPLAM		FLOAT,
	@ORAN			FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS


DECLARE @NOBONUSTUTAR FLOAT

SELECT @NOBONUSTUTAR = SUM(TUTAR) 
FROM TBL_BEKLETME_DETAY
WHERE FISID IN (
				SELECT ID FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
				) AND
BARKOD IN (SELECT BARKOD FROM TBL_STOK_MAIN WHERE ISNULL(REYONADI,'') = 'NOBONUS')

SET @NOBONUSTUTAR = ISNULL(@NOBONUSTUTAR,0)

SET @ARATOPLAM = @ARATOPLAM - @NOBONUSTUTAR

DECLARE @NEWARATOPLAM FLOAT 

SET @NEWARATOPLAM = @ARATOPLAM + ((@ARATOPLAM * @ORAN) / 100.00)

SET DATEFORMAT mdy; 

DECLARE @CARIGRUP VARCHAR(20)

IF ISNULL(@CARIKODU,'') <> ''
	SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

SET @CARIGRUP = ISNULL(@CARIGRUP,'')

IF @CARITIPI = 'M' SET @CARITIPI = NULL
	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
		CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END,
		CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
			CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
		ELSE
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		END
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @NEWARATOPLAM AND 
		ARATOPLAM > @ARATOPLAM AND
		CARIGRUP = @CARIGRUP AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		PUAN = 0 AND
		ISNULL(PUANYUZDE,0) = 0
	ORDER BY ARATOPLAM DESC
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('05','07'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END,
			CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @NEWARATOPLAM AND 
			ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = '' AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			PUAN = 0 AND
			ISNULL(PUANYUZDE,0) = 0
		ORDER BY ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		TOP 1
		'09',
		U.INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (SELECT STOKKODU, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
		LEFT JOIN (
						SELECT S.STOKKODU, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU 
	WHERE 
		U.ARATOPLAM <= @NEWARATOPLAM AND 
		U.ARATOPLAM > @ARATOPLAM AND
		CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 0
	ORDER BY U.ARATOPLAM DESC
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'09',
		U.INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (SELECT STOKKODU, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
		LEFT JOIN (
						SELECT S.STOKKODU, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU 
	WHERE 
		U.ARATOPLAM <= @NEWARATOPLAM AND 
		U.ARATOPLAM > @ARATOPLAM AND
		CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 1
	ORDER BY U.ARATOPLAM ASC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('09'))
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			TOP 1
			'09',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (SELECT STOKKODU, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
			LEFT JOIN (
							SELECT S.STOKKODU, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.VSTOKKODU 
		WHERE 
			U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC
	
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'09',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ISNULL(D.TUTAR, S.FIYAT) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (SELECT STOKKODU, STOKADI, MAX(S.FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
			LEFT JOIN (
							SELECT S.STOKKODU, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.VSTOKKODU 
		WHERE 
			U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 1
		ORDER BY U.ARATOPLAM ASC
	END

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		TOP 1
		'39',
		U.INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		LEFT JOIN (
						SELECT S.STOKKODU, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU 
		INNER JOIN (SELECT STOKKODU, STOKADI, MAX(FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		CARIGRUP = @CARIGRUP AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI)  AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		D.STOKKODU IS NULL
	ORDER BY U.ARATOPLAM DESC	

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('39'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			TOP 1
			'39',
			U.INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL''YE '+SUBSTRING(S.STOKADI,1,20)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (S.FIYAT * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			LEFT JOIN (
							SELECT S.STOKKODU FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU 
			INNER JOIN (SELECT STOKKODU, STOKADI, MAX(FIYAT) AS FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			CARIGRUP = '' AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			D.STOKKODU IS NULL
		ORDER BY U.ARATOPLAM DESC	
	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'10',
		0,
		U.INDTUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL''YE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(U.INDTUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		U.ARATOPLAM <= @NEWARATOPLAM AND 
		U.ARATOPLAM > @ARATOPLAM AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		CARIGRUP = @CARIGRUP AND
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR >  ISNULL(@INDTUTAR,0)
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('10'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'10',
			0,
			U.INDTUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL''YE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(U.INDTUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			CARIGRUP = '' AND
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR >  ISNULL(@INDTUTAR,0)
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'11',
		0,
		0,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL''YE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜ HEDİYE',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		U.ARATOPLAM <= @NEWARATOPLAM AND 
		U.ARATOPLAM > @ARATOPLAM AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		CARIGRUP = @CARIGRUP AND
		U.INDTUTAR = 0 AND
		U.INDYUZDE = 0 
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'11',
			0,
			0,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL''YE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜ HEDİYE',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			U.ARATOPLAM <= @NEWARATOPLAM AND 
			U.ARATOPLAM > @ARATOPLAM AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			CARIGRUP = '' AND
			U.INDTUTAR = 0 AND
			U.INDYUZDE = 0 
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		'27' ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
		CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
				END
		END,
		CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
			CONVERT(VARCHAR, 
								CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
										CASE 
											WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
											ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
										END
								END
			)+' PUAN'
		ELSE
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		END
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @NEWARATOPLAM AND 
		ARATOPLAM > @ARATOPLAM AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		CARIGRUP = @CARIGRUP AND
		(
			PUAN > 0 OR
			ISNULL(PUANYUZDE,0) > 0
		) AND
		INDYUZDE = 0 AND
		INDTUTAR = 0
	ORDER BY ARATOPLAM DESC
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) > 0 THEN
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.'
		ELSE
		CONVERT(VARCHAR, PUAN) +' PUAN' END,
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM > 0 AND 
		H.TUTAR < ARATOPLAM AND
		H.TUTAR + ((H.TUTAR * @ORAN) / 100.00) >= ARATOPLAM 
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			'27' ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
					CASE 
						WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
						ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
					END
			END,
			CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL''YE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, 
								CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
										CASE 
											WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@NEWARATOPLAM * PUANYUZDE) / 100.00,2)
											ELSE FLOOR(@NEWARATOPLAM / ARATOPLAM) * PUAN 
										END
								END
				)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @NEWARATOPLAM AND 
			ARATOPLAM > @ARATOPLAM AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			CARIGRUP = '' AND
			(
				PUAN > 0 OR
				ISNULL(PUANYUZDE,0) > 0
			) AND
			INDYUZDE = 0 AND
			INDTUTAR = 0
		ORDER BY ARATOPLAM DESC
		
	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_IBM_KONTROL] 
	@CARITIPI		VARCHAR(1) ,
	@ARATOPLAM		FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 


DECLARE @NOBONUSTUTAR FLOAT

SELECT @NOBONUSTUTAR = SUM(TUTAR) 
FROM TBL_BEKLETME_DETAY
WHERE FISID IN (
				SELECT ID FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
				) AND
BARKOD IN (SELECT BARKOD FROM TBL_STOK_MAIN WHERE ISNULL(REYONADI,'') = 'NOBONUS')

SET @NOBONUSTUTAR = ISNULL(@NOBONUSTUTAR,0)

SET @ARATOPLAM = @ARATOPLAM - @NOBONUSTUTAR

DECLARE @CARIGRUP VARCHAR(20)

IF ISNULL(@CARIKODU,'') <> ''
	SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

SET @CARIGRUP = ISNULL(@CARIGRUP,'')


IF @CARITIPI = 'M' SET @CARITIPI = NULL

	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		'15' AS INDIRIMTIPI,
		0,
		ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
		CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.STOKKODU, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.STOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
	WHERE 
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		CARIGRUP = @CARIGRUP AND
		VREYONADI = '' AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) > 1  AND
		D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '15')
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			'15' AS INDIRIMTIPI,
			0,
			ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
			CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.STOKKODU, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.STOKKODU
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
		WHERE 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			CARIGRUP = '' AND
			VREYONADI = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) > 1  AND
			D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
		CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END,
		CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
			CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
		ELSE
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		END
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @ARATOPLAM AND 
		CARIGRUP = @CARIGRUP AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		PUAN = 0 AND
		ISNULL(PUANYUZDE,0) = 0
	ORDER BY ARATOPLAM DESC
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('05','07'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			CARIGRUP = '' AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			PUAN = 0 AND
			ISNULL(PUANYUZDE,0) = 0
		ORDER BY ARATOPLAM DESC
	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		TOP 1
		'09',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2)		
		 AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 0
	ORDER BY U.ARATOPLAM DESC
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'09',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END,2)		
		 AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 1
	ORDER BY U.ARATOPLAM ASC
		
		
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('09'))
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			TOP 1
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 1
		ORDER BY U.ARATOPLAM ASC
	
	END

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'10',
		0,
		U.INDTUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(U.INDTUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR >  ISNULL(@INDTUTAR,0)
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('10'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'10',
			0,
			U.INDTUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(U.INDTUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR >  ISNULL(@INDTUTAR,0)
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'11',
		0,
		D.TUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR = 0 AND
		U.INDYUZDE = 0 
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'11',
			0,
			D.TUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR = 0 AND
			U.INDYUZDE = 0 
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
		0,
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
		CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN
	FROM (
			SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
			GROUP BY S.STOKKODU
			HAVING SUM(MIKTAR) > 0
		) AS D 
		INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.STOKKODU = D.STOKKODU AND A.STOKKODU = A.VSTOKKODU AND A.CARIGRUP = @CARIGRUP
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = A.STOKKODU
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0	AND
		A.VMIKTAR <> 0	
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('14','16'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT 
			CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
			0,
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
			CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN
		FROM (
				SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
				FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
					INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
					INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
				GROUP BY S.STOKKODU
				HAVING SUM(MIKTAR) > 0
			) AS D 
			INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.STOKKODU = D.STOKKODU AND A.STOKKODU = A.VSTOKKODU AND A.CARIGRUP = ''
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = A.STOKKODU
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0 AND
			A.VMIKTAR <> 0	
	
	CREATE TABLE #PROMOSYONTBL(ASTOKKODU VARCHAR(20), VSTOKKODU VARCHAR(20), VREYONADI VARCHAR(20)  COLLATE TURKISH_CI_AS, AMIKTAR FLOAT, VMIKTAR FLOAT, ALINANMIKTAR FLOAT, VERILENMIKTAR FLOAT, VERILENBIRIMFIYAT FLOAT, PUAN FLOAT, SATIR INT, INDYUZDE FLOAT, INDTUTAR FLOAT)		

	INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT STOKKODU, VSTOKKODU, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.CARIGRUP = @CARIGRUP AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
		A.STOKKODU <> A.VSTOKKODU 
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 1)
		INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT STOKKODU, VSTOKKODU, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.CARIGRUP = '' AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.STOKKODU <> A.VSTOKKODU 
		
	INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT STOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P2' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
		A.CARIGRUP = @CARIGRUP AND
		ISNULL(VREYONADI,'') <> ''

	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 2)
		INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT STOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P2' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.CARIGRUP = '' AND
			ISNULL(VREYONADI,'') <> ''

	UPDATE #PROMOSYONTBL
	SET	VSTOKKODU = H.STOKKODU
	FROM #PROMOSYONTBL P
		INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.REYONADI  COLLATE TURKISH_CI_AS = P.VREYONADI
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) H ON H.STOKKODU = S.STOKKODU
	WHERE P.VREYONADI <> ''
	
	UPDATE #PROMOSYONTBL
	SET ALINANMIKTAR = H.MIKTAR
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) H ON H.STOKKODU = P.ASTOKKODU

	UPDATE #PROMOSYONTBL
	SET VERILENMIKTAR = H.MIKTAR,
		VERILENBIRIMFIYAT = CASE WHEN VERILENBIRIMFIYAT > 0 THEN VERILENBIRIMFIYAT ELSE H.BIRIMFIYAT END
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) H ON H.STOKKODU = P.VSTOKKODU

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'18',
		0,
		(CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								((CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END)) 
								AS MONEY
							)		 
						,1)
		+' TL İND',
		FLOOR(ALINANMIKTAR / AMIKTAR) * PUAN
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS A ON A.STOKKODU = P.ASTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS V ON V.STOKKODU = P.VSTOKKODU
	WHERE 
		VMIKTAR = 0 AND
		ALINANMIKTAR <> 0 AND 
		VERILENMIKTAR <> 0 AND
		FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, A.STOKADI, INDYUZDE, INDTUTAR  	
	
	DELETE FROM #PROMOSYONTBL
	WHERE VMIKTAR = 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'17',
		0,
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								CASE 
									WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
										THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
										ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
									ELSE 0 
								END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END) AS MONEY
							)		 
						,1)
		+' TL İND',
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * PUAN
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS A ON A.STOKKODU = P.ASTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS V ON V.STOKKODU = P.VSTOKKODU
	WHERE ALINANMIKTAR <> 0 AND VERILENMIKTAR <> 0 AND
		(CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END)) <> 0
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, A.STOKADI, INDYUZDE  	
		

	DROP TABLE #PROMOSYONTBL

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '28' ELSE '29' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, FLOOR(H.MIKTAR / P.AMIKTAR) * P.AMIKTAR)+' ADET ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM = 0 AND
		P.AMIKTAR > 0 AND
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) > 0 AND
		ISKADEMELI = 0
		

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.STOKKODU, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) L ON L.STOKKODU = P.VSTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = L.STOKKODU
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.VMIKTAR * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
						HAVING SUM(MIKTAR) > 0
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.STOKKODU, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
					) L ON L.STOKKODU = P.VSTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = L.STOKKODU
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		0,
		CASE 
			WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
		ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
		END,
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, (FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR))+' ADET ALANA '+
		CONVERT(VARCHAR, CAST( 
								CASE 
									WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
								ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
								END		
							AS MONEY), 1)+' TL İND.',
		(FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.MIKTAR) AS MIKTAR, MIN(D.FIYAT) AS FIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		AMIKTAR <> 0 AND 
		VMIKTAR <> 0 AND 
		H.MIKTAR >= AMIKTAR AND
		ISKADEMELI = 0 AND
		ARATOPLAM = 0 AND
		(
			(P.INDYUZDE <> 0) OR
			(P.INDTUTAR <> 0)
		)
		 
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'26',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN H.MIKTAR * INDTUTAR ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN ALDIĞINIZ ÜRÜNLER İÇİN '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN H.MIKTAR * INDTUTAR ELSE (H.TUTAR * INDYUZDE) / 100.00  END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 1 AND 
		VMIKTAR = 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	IF EXISTS(
				SELECT TOP 1 1 FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
				INNER JOIN (
								SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
								FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
									INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
									INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
								GROUP BY S.REYONADI
							) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
				WHERE 
					P.BASLANGICTARIHI <= GETDATE() AND
					P.BITISTARIHI >= GETDATE() AND
					P.PROMOSYONTIPI = 'P7' AND 
					P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
					P.CARIGRUP = @CARIGRUP AND
					P.REYONADI <> '' AND 
					VPLUNO = 0 AND 
					H.TUTAR >= ARATOPLAM AND
					ISKADEMELI = 1
			)
	BEGIN
		DECLARE @REYONADI		VARCHAR(20),
				@REYONINDYUZDE	FLOAT,
				@REYONINDTUTAR	FLOAT,
				@STOKSTOKKODU	VARCHAR(20),
				@STOKMIKTAR		FLOAT,
				@STOKFIYAT		FLOAT,
				@ADET			FLOAT
				
		
		CREATE TABLE #STABLE(ID INT IDENTITY(1,1) PRIMARY KEY, STOKKODU VARCHAR(20), FIYAT FLOAT, INDTUTAR FLOAT, SIRANO INT)

		DECLARE CURREYON CURSOR FAST_FORWARD FOR
		SELECT P.REYONADI, P.INDYUZDE, P.INDTUTAR FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		WHERE 
			P.BASLANGICTARIHI <= GETDATE() AND
			P.BITISTARIHI >= GETDATE() AND
			P.PROMOSYONTIPI = 'P7' AND 
			P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
			P.CARIGRUP = @CARIGRUP AND
			P.REYONADI <> '' AND 
			VPLUNO = 0 AND 
			H.TUTAR >= ARATOPLAM AND
			ISKADEMELI = 1
		OPEN CURREYON
		
		FETCH NEXT FROM CURREYON
		INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE FROM #STABLE	
			
			DECLARE CURRSTOK CURSOR FAST_FORWARD FOR
			SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) / SUM(MIKTAR) AS FIYAT
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
			WHERE S.REYONADI = @REYONADI 
			GROUP BY S.STOKKODU
			HAVING (SUM(MIKTAR) <> 0) AND (SUM(MIKTAR) - FLOOR(SUM(MIKTAR)) = 0)
			OPEN CURRSTOK
			
			FETCH NEXT FROM CURRSTOK
			INTO @STOKSTOKKODU, @STOKMIKTAR, @STOKFIYAT
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ADET = @STOKMIKTAR
				
				WHILE @ADET > 0 
				BEGIN
					INSERT INTO #STABLE(STOKKODU, FIYAT, INDTUTAR, SIRANO)
					SELECT @STOKSTOKKODU, @STOKFIYAT, CASE WHEN @REYONINDYUZDE = 0 THEN @REYONINDTUTAR ELSE ROUND((@STOKFIYAT * @REYONINDYUZDE) / 100.00,2) END, 0
					
					SET @ADET = @ADET - 1
				END
			
				FETCH NEXT FROM CURRSTOK
				INTO @STOKSTOKKODU, @STOKMIKTAR, @STOKFIYAT
			END
			
			CLOSE CURRSTOK
			DEALLOCATE CURRSTOK
			
			UPDATE #STABLE
			SET SIRANO = H.SIRANO
			FROM #STABLE S
				INNER JOIN (SELECT ID, ROW_NUMBER() OVER(ORDER BY FIYAT DESC) AS SIRANO FROM #STABLE) AS H ON H.ID = S.ID
			
			DELETE FROM #STABLE 
			WHERE SIRANO % 2 <> 0

			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
			SELECT 
				'30',
				@REYONINDYUZDE,
				ROUND(INDTUTAR,2),
				SUBSTRING(M.STOKADI,1,20)+' KADEMELİ '+CONVERT(VARCHAR, CAST(INDTUTAR AS MONEY), 1)+' TL İND.',
				0
			FROM #STABLE S
				INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS M ON M.STOKKODU = S.STOKKODU
			WHERE INDTUTAR <> 0
			ORDER BY INDTUTAR DESC
			
			FETCH NEXT FROM CURREYON
			INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		END
		
		CLOSE CURREYON
		DEALLOCATE CURREYON		
		
		DROP TABLE #STABLE
	END
	
	DECLARE @TOPLAMINDIRIM FLOAT
	
	SELECT @TOPLAMINDIRIM  = SUM(INDTUTAR) FROM #RETTABLE
	
	SET @ARATOPLAM = @ARATOPLAM - ABS(ISNULL(@TOPLAMINDIRIM,0))
	
	IF @ARATOPLAM > 0
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			'27',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
				END
			END,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, 
								CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
									CASE 
										WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
										ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
									END
								END
				)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			CARIGRUP = @CARIGRUP AND
			(
				PUAN > 0 OR
				ISNULL(PUANYUZDE,0) > 0
			) AND
			INDYUZDE = 0 AND
			INDTUTAR = 0
		ORDER BY ARATOPLAM DESC
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '27')
			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
			SELECT  
				TOP 1
				'27',
				INDYUZDE,
				ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
				CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
					CASE 
						WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
						ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
					END
				END,
				CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
				CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
					CONVERT(VARCHAR, 
									CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
										CASE 
											WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
											ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
										END
									END
					)+' PUAN'
				ELSE
					CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
				END
			FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			WHERE 
				ARATOPLAM <= @ARATOPLAM AND 
				BASLANGICTARIHI <= GETDATE() AND
				BITISTARIHI >= GETDATE() AND
				PROMOSYONTIPI = 'P1' AND 
				CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
				CARIGRUP = '' AND
				(
					PUAN > 0 OR
					ISNULL(PUANYUZDE,0) > 0
				) AND
				INDYUZDE = 0 AND
				INDTUTAR = 0
			ORDER BY ARATOPLAM DESC
		
	END

	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_PROMOSYON_IBM_FILE]
AS

SET DATEFORMAT mdy 

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRAN

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, SUBSTRING(DATA,6,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,9,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,16,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,19,10),'.',''))/100 AS INDTUTAR,
			1 AS VMIKTAR,
			0 AS VPLUNO,
			'' AS VSTOKKODU,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			SUBSTRING(DATA,74,20) AS REYONADI,
			CONVERT(INT, SUBSTRING(DATA,95,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,101,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,122,20)) AS STOKKODU
		INTO #TEMPFILE FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P2'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	TRUNCATE TABLE TBL_PROMOSYON_URUN
	TRUNCATE TABLE TBL_PROMOSYON_TUTAR
	TRUNCATE TABLE TBL_PROMOSYON_REYON
	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP, STOKKODU, VSTOKKODU)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ISNULL(REYONADI,''), PUAN, CARIGRUP, STOKKODU, VSTOKKODU
		FROM #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	DROP TABLE #TEMPFILE 
	
	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,17,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,20,10),'.',''))/100 AS INDTUTAR,
			SUBSTRING(DATA,32,1) AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,74,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,80,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,101,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE2 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P1'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 0, 0, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, PUANYUZDE
		FROM #TEMPFILE2
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE2
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE2

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,27,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,31,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,46,2)+'-'+SUBSTRING(DATA,43,2)+SUBSTRING(DATA,48,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,66,2)+'-'+SUBSTRING(DATA,63,2)+SUBSTRING(DATA,68,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,83,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,89,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(BIT, SUBSTRING(DATA,110,1)) AS TUMURUNLER,
			RTRIM(SUBSTRING(DATA,112,20)) AS VSTOKKODU,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,133,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE3 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P4') AND CONVERT(INT, SUBSTRING(DATA,20,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, VSTOKKODU, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, TUMURUNLER, VSTOKKODU, PUANYUZDE
		FROM #TEMPFILE3
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE3
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE3

	BEGIN TRY
		SELECT
			'P4' AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,17,6)) AS VPLUNO,
			0 AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,79,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,85,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,106,20)) AS VSTOKKODU,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,127,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE4 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PF') AND CONVERT(INT, SUBSTRING(DATA,17,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, VSTOKKODU, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, 0, VSTOKKODU, PUANYUZDE
		FROM #TEMPFILE4
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE4
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE4

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			0 AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			RTRIM(SUBSTRING(DATA,79,20)) AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,100,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,106,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,127,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE5 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PR') AND RTRIM(SUBSTRING(DATA,79,20)) <> ''
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, VSTOKKODU, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, '', PUANYUZDE
		FROM #TEMPFILE5
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE5
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE5

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(INT, SUBSTRING(DATA,6,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,13,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,16,6)) AS VPLUNO,
			CONVERT(FLOAT, REPLACE(REPLACE(SUBSTRING(DATA,23,2),'--','0'),' ','0')) AS VMIKTAR, 
			CONVERT(FLOAT, SUBSTRING(DATA,26,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,29,10),'.',''))/100 AS INDTUTAR,
			CONVERT(DATETIME, SUBSTRING(DATA,44,2)+'-'+SUBSTRING(DATA,41,2)+SUBSTRING(DATA,46,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,64,2)+'-'+SUBSTRING(DATA,61,2)+SUBSTRING(DATA,66,14)) AS BITISTARIHI,
			'' AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,81,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,87,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,108,20)) AS STOKKODU,
			RTRIM(SUBSTRING(DATA,129,20)) AS VSTOKKODU
		INTO #TEMPFILE6 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P3') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP, STOKKODU, VSTOKKODU)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP, STOKKODU, VSTOKKODU
		FROM #TEMPFILE6
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE6
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE6

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			RTRIM(SUBSTRING(DATA,6,20)) AS REYONADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,38,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,42,10),'.',''))/100 AS INDTUTAR,
			CONVERT(INT, SUBSTRING(DATA,53,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,60,2)) AS VMIKTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,92,2)+'-'+SUBSTRING(DATA,89,2)+SUBSTRING(DATA,94,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,112,2)+'-'+SUBSTRING(DATA,109,2)+SUBSTRING(DATA,114,14)) AS BITISTARIHI,
			CONVERT(FLOAT, SUBSTRING(DATA,129,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,132,5)) AS PUAN,
			CONVERT(BIT, SUBSTRING(DATA,138,1)) AS ISKADEMELI,
			RTRIM(SUBSTRING(DATA,140,20)) AS VSTOKKODU,
			RTRIM(SUBSTRING(DATA,161,255)) AS CARIGRUP
		INTO #TEMPFILE7 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P7') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P7 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_REYON(PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, VSTOKKODU, CARIGRUP)
		SELECT
			PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, VSTOKKODU, CARIGRUP
		FROM #TEMPFILE7
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE7
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P7 TBL_PROMOSYON_REYON TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE7

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_TEKRAR_LIST]
	@BELGEKODU VARCHAR(20), 
	@TARIH SMALLDATETIME
AS
	SELECT TOP 500 ID, dbo.ZL(DATEPART(DD,TARIH),2)+'/'+dbo.ZL(DATEPART(MM,TARIH),2)+' '+dbo.ZL(DATEPART(HH,TARIH),2)+':'+dbo.ZL(DATEPART(MINUTE,TARIH),2) AS TARIH, CONVERT(BIT, CASE WHEN ISNULL(EFATURAKODU, '') <> '' THEN 1 ELSE 0 END) AS ISEARSIV, BELGEKODU, TUTAR, CASE TIP WHEN 1 THEN CASE WHEN ISEFATURA = 1 THEN 'E-FATURA' ELSE 'FATURA' END WHEN 2 THEN 'IADE' WHEN 3 THEN 'IPT' WHEN 8 THEN 'IRS' ELSE CASE WHEN ISNULL(EFATURAKODU, '') <> '' THEN 'E-ARSIV' ELSE 'FIS' END END AS TIPADI, TIP FROM TBL_FIS_MAIN WITH (NOLOCK) 
	WHERE BELGEKODU = dbo.ZL(@BELGEKODU,6) AND CONVERT(SMALLDATETIME, CONVERT(VARCHAR, TARIH, 112)) = @TARIH
	ORDER BY ID DESC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_DETAY_INSERT]
	@FISID			INT,
	@SATIRNO		INT,
	@TIP			VARCHAR(3),
	@PLUNO			INT,
	@BARKOD			VARCHAR(20),
	@STOKKODU		VARCHAR(20),
	@STOKADI		VARCHAR(50),
	@KDV			FLOAT,
	@DEPARTMAN		INT,
	@MIKTAR			FLOAT,
	@BIRIM			VARCHAR(10),
	@FIYAT			FLOAT,
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PLASIYERKODU	VARCHAR(4),
	@PLASIYERADI	VARCHAR(20),
	@ACIKLAMA		VARCHAR(MAX),
	@BARKODTYPE		TINYINT,
	@DOVIZKODU		VARCHAR(10),
	@DOVIZKURU		FLOAT,
	@DOVIZTUTARI	FLOAT,
	@PUAN			FLOAT,
	@TEVKIFATKODU	VARCHAR(10),
	@TEVKIFATACIKLAMA VARCHAR(100),
	@TEVKIFATORANI	INT,
	@OTVKODU	VARCHAR(10),
	@OTVACIKLAMA VARCHAR(100),
	@OTVORANI	INT
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_DETAY(FISID, SATIRNO, TIP, PLUNO, BARKOD, STOKKODU, STOKADI, KDV, DEPARTMAN, MIKTAR, BIRIM, FIYAT, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PLASIYERKODU, PLASIYERADI, ACIKLAMA, BARKODTYPE, DOVIZKODU, DOVIZKURU, DOVIZTUTARI, PUAN, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI)
	SELECT @FISID, @SATIRNO, @TIP, @PLUNO, @BARKOD, @STOKKODU, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PLASIYERKODU, @PLASIYERADI, @ACIKLAMA, @BARKODTYPE, @DOVIZKODU, @DOVIZKURU, @DOVIZTUTARI, @PUAN, @TEVKIFATKODU, @TEVKIFATACIKLAMA, @TEVKIFATORANI, @OTVKODU, @OTVACIKLAMA, @OTVORANI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_BEKLETME_DETAY_INSERT]
	@FISID			INT,
	@SATIRNO		INT,
	@TIP			VARCHAR(3),
	@PLUNO			INT,
	@BARKOD			VARCHAR(20),
	@STOKKODU		VARCHAR(20),
	@STOKADI		VARCHAR(50),
	@KDV			FLOAT,
	@DEPARTMAN		INT,
	@MIKTAR			FLOAT,
	@BIRIM			VARCHAR(10),
	@FIYAT			FLOAT,
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PLASIYERKODU	VARCHAR(4),
	@PLASIYERADI	VARCHAR(20),
	@ACIKLAMA		VARCHAR(MAX),
	@BARKODTYPE		TINYINT,
	@DOVIZKODU		VARCHAR(10),
	@DOVIZKURU		FLOAT,
	@DOVIZTUTARI	FLOAT,
	@PUAN			FLOAT,
	@TEVKIFATKODU	VARCHAR(10),
	@TEVKIFATACIKLAMA VARCHAR(100),
	@TEVKIFATORANI	INT,
	@OTVKODU	VARCHAR(10),
	@OTVACIKLAMA VARCHAR(100),
	@OTVORANI	INT
AS
	SET NOCOUNT ON
	DECLARE @ID INT

	SELECT @ID = ID FROM TBL_BEKLETME_DETAY WITH (NOLOCK)
	WHERE FISID = @FISID AND SATIRNO = @SATIRNO
	IF @ID IS NULL
		INSERT INTO TBL_BEKLETME_DETAY(FISID, SATIRNO, TIP, PLUNO, BARKOD, STOKKODU, STOKADI, KDV, DEPARTMAN, MIKTAR, BIRIM, FIYAT, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PLASIYERKODU, PLASIYERADI, ACIKLAMA, BARKODTYPE, DOVIZKODU, DOVIZKURU, DOVIZTUTARI, PUAN, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI)
		SELECT @FISID, @SATIRNO, @TIP, @PLUNO, @BARKOD, @STOKKODU, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PLASIYERKODU, @PLASIYERADI, @ACIKLAMA, @BARKODTYPE, @DOVIZKODU, @DOVIZKURU, @DOVIZTUTARI, @PUAN, @TEVKIFATKODU, @TEVKIFATACIKLAMA, @TEVKIFATORANI, @OTVKODU, @OTVACIKLAMA, @OTVORANI
	ELSE
		UPDATE TBL_BEKLETME_DETAY
		SET
			TIP				= @TIP				,
			PLUNO			= @PLUNO			,
			BARKOD			= @BARKOD			,
			STOKKODU		= @STOKKODU			,
			STOKADI			= @STOKADI			,
			KDV				= @KDV				,
			DEPARTMAN		= @DEPARTMAN		,
			MIKTAR			= @MIKTAR			,
			BIRIM			= @BIRIM			,
			FIYAT			= @FIYAT			,
			TUTAR			= @TUTAR			,
			INDYUZDE		= @INDYUZDE			,
			INDTUTAR		= @INDTUTAR			,
			ARTYUZDE		= @ARTYUZDE			,
			ARTTUTAR		= @ARTTUTAR			,
			KASIYERKODU		= @KASIYERKODU		,
			KASIYERADI		= @KASIYERADI		,
			PLASIYERKODU	= @PLASIYERKODU		,
			PLASIYERADI		= @PLASIYERADI		,
			ACIKLAMA		= @ACIKLAMA			,
			BARKODTYPE		= @BARKODTYPE		,
			DOVIZKODU		= @DOVIZKODU		, 
			DOVIZKURU		= @DOVIZKURU		, 
			DOVIZTUTARI		= @DOVIZTUTARI		,
			PUAN			= @PUAN				,
			TEVKIFATKODU	= @TEVKIFATKODU		,
			TEVKIFATACIKLAMA= @TEVKIFATACIKLAMA	,
			TEVKIFATORANI	= @TEVKIFATORANI	,
			OTVKODU			= @OTVKODU			,
			OTVACIKLAMA		= @OTVACIKLAMA		,
			OTVORANI		= @OTVORANI			
		WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_KASIYER_FILE]
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRY
	SELECT
		CONVERT(INT, SUBSTRING(DATA,2,4)) AS USERCODE,
		RTRIM(SUBSTRING(DATA,6,20)) AS USERNAME,
		LTRIM(RTRIM(SUBSTRING(DATA,26,6))) AS PASSWORD,
		SUBSTRING(DATA,32,1) AS YETKI,
		CONVERT(DECIMAL(4,2), SUBSTRING(DATA,33,2)) AS YUZDE,
		CONVERT(DECIMAL(21,6), SUBSTRING(DATA,35,10))/100 AS TUTAR
	INTO #TEMPFILE FROM TBL_IMPORT_FILE
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : KASİYER DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

BEGIN TRAN

	DELETE TBL_USER_MAIN
	WHERE ID > 1

	BEGIN TRY
		INSERT INTO TBL_USER_MAIN(USERCODE, USERNAME, YETKI, ADMIN, PASSWORD, CREATEDATE, YUZDEINDIRIMLIMITI, TUTARINDIRIMLIMITI)
		SELECT USERCODE, USERNAME, YETKI, CASE WHEN YETKI = 'A' THEN 1 ELSE 0 END, PASSWORD, GETDATE(), YUZDE, TUTAR FROM #TEMPFILE
		WHERE USERCODE NOT IN (SELECT USERCODE FROM TBL_USER_MAIN WITH (NOLOCK))
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_USER_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

DROP TABLE #TEMPFILE

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_USER_MAIN_LIST]
	@ID		  INT = NULL,
	@USERCODE VARCHAR(100) = NULL,
	@PASSWORD VARCHAR(6) = NULL,
	@USERNAME VARCHAR(50) = NULL
AS
	IF @ID IS NOT NULL
		SELECT
			ID,
			USERCODE,
			USERNAME,
			YETKI,
			ADMIN,
			PASSWORD,
			YUZDEINDIRIMLIMITI,
			TUTARINDIRIMLIMITI
		FROM TBL_USER_MAIN WITH (NOLOCK)
		WHERE ID = @ID
	ELSE IF @USERNAME IS NOT NULL
		SELECT
			ID,
			USERCODE,
			USERNAME,
			YETKI,
			ADMIN,
			PASSWORD,
			YUZDEINDIRIMLIMITI,
			TUTARINDIRIMLIMITI
		FROM TBL_USER_MAIN WITH (NOLOCK)
		WHERE
			USERNAME LIKE ISNULL('%'+@USERNAME+'%', USERNAME) 
		ORDER BY USERNAME
	ELSE
		SELECT
			ID,
			USERCODE,
			USERNAME,
			YETKI,
			ADMIN,
			PASSWORD,
			YUZDEINDIRIMLIMITI,
			TUTARINDIRIMLIMITI
		FROM TBL_USER_MAIN WITH (NOLOCK)
		WHERE
			USERCODE = ISNULL(@USERCODE, USERCODE) AND
			PASSWORD = ISNULL(@PASSWORD, PASSWORD)
		ORDER BY USERNAME
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_CARI_IBM_FILE]
AS
SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX),
	@MAXCARINO INT

SELECT @MAXCARINO = MAX(CARINO) FROM TBL_CARI_MAIN WITH (NOLOCK)
SET @MAXCARINO = ISNULL(@MAXCARINO,0)+1

BEGIN TRY
	SELECT
		CONVERT(TINYINT, SUBSTRING(DATA,5,1)) AS DURUM,
		1 AS FIYATTIPNO,
		RTRIM(SUBSTRING(DATA,6,24)) AS CARIKODU,
		RTRIM(SUBSTRING(DATA,54,30)) AS CARIADI,
		SUBSTRING(RTRIM(SUBSTRING(DATA,124,90)) + RTRIM(SUBSTRING(DATA,214,20)),1,60) AS ADRES,
		RTRIM(SUBSTRING(DATA,394,20)) AS VERGIDAIRESI,
		RTRIM(SUBSTRING(DATA,414,12)) AS VERGINO,
		CONVERT(INT, REPLACE(REPLACE(SUBSTRING(DATA,461,6),'.',''),',','')) AS INDIRIM,
		0 AS ISEFATURA,
		RTRIM(SUBSTRING(DATA,319,25)) AS EMAIL,
		'S' AS CARITIPI,
		RTRIM(SUBSTRING(DATA,244,20)) TELEFON,
		RTRIM(SUBSTRING(DATA,84,8)) AS GRUP,
		CONVERT(BIT, 0) AS ISINSERTTELEFON
	INTO #TEMPFILE FROM TBL_IMPORT_FILE
	WHERE DATA LIKE '01%'
	

	UPDATE #TEMPFILE
	SET TELEFON = ''
	WHERE 
		(TELEFON NOT LIKE '905%' AND
		TELEFON NOT LIKE '5%' AND
		TELEFON NOT LIKE '05%') OR
		LEN(TELEFON) > 17 
	
	DELETE FROM #TEMPFILE
	WHERE CARIKODU IN (
						SELECT CARIKODU FROM #TEMPFILE
						GROUP BY CARIKODU
						HAVING COUNT(*) > 1
						)

	ALTER TABLE #TEMPFILE ADD ID INT IDENTITY(1,1) PRIMARY KEY

	UPDATE #TEMPFILE
	SET TELEFON = REPLACE(TELEFON,' ', '')
	WHERE LEN(REPLACE(TELEFON,' ', '')) >= 10

	UPDATE #TEMPFILE
	SET TELEFON = CASE WHEN SUBSTRING(TELEFON,1,2) = '05' THEN '9'+TELEFON WHEN SUBSTRING(TELEFON,1,1) = '5' THEN '90'+TELEFON ELSE TELEFON END
	WHERE LEN(TELEFON) >= 10

	UPDATE #TEMPFILE
	SET TELEFON = ''
	WHERE TELEFON NOT LIKE '905%'
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : CARİ DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : CARI DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

BEGIN TRAN

	BEGIN TRY
		DELETE FROM TBL_CARI_MAIN
		WHERE CARIKODU IN (SELECT CARIKODU FROM #TEMPFILE WHERE DURUM = 2)
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		UPDATE TBL_CARI_MAIN
		SET  
			CARIADI	= T.CARIADI, 
			ADRES	= T.ADRES, 
			VERGIDAIRESI = T.VERGIDAIRESI, 
			VERGINO = T.VERGINO, 
			INDIRIM = T.INDIRIM, 
			GRUP = T.GRUP, 
			CREATEDATE = GETDATE(), 
			CREATEUSERCODE = APP_NAME(), 
			EMAIL = T.EMAIL, 
			TELEFON = T.TELEFON
		FROM TBL_CARI_MAIN C 
			INNER JOIN #TEMPFILE T ON T.CARIKODU = C.CARIKODU
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNA KAYIT GÜNCELLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_CARI_MAIN(CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON)
		SELECT @MAXCARINO + ID, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, GETDATE(), APP_NAME(), FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON
		FROM  #TEMPFILE
		WHERE CARIKODU NOT IN (SELECT CARIKODU FROM TBL_CARI_MAIN WITH (NOLOCK))
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		SELECT ID, CARIKODU, REPLACE(TELEFON,' ','') AS TELEFON, CONVERT(BIT, 0) AS ISDELETE INTO #TMP 
		FROM TBL_CARI_MAIN WITH (NOLOCK)
		WHERE LEN(REPLACE(TELEFON,' ','')) >= 10 

		UPDATE #TMP
		SET TELEFON = CASE WHEN SUBSTRING(TELEFON,1,2) = '05' THEN '9'+TELEFON WHEN SUBSTRING(TELEFON,1,1) = '5' THEN '90'+TELEFON ELSE TELEFON END

		UPDATE #TMP
		SET ISDELETE = 1
		FROM #TMP C
			INNER JOIN TBL_CARI_TELEFON T WITH (NOLOCK) ON T.CARIKODU = C.CARIKODU AND T.TELEFON = C.TELEFON

		DELETE FROM #TMP
		WHERE ISDELETE = 1

		INSERT INTO TBL_CARI_TELEFON(CARIKODU, TELEFON)
		SELECT CARIKODU, TELEFON FROM #TMP
		WHERE ID IN (
						SELECT MAX(ID) FROM #TMP
						WHERE 
							TELEFON LIKE '905%' AND
							LEN(TELEFON) = 12 AND
							TELEFON NOT LIKE '%[a-z][A-Z]%'
						GROUP BY TELEFON
					) AND 
		TELEFON NOT IN (SELECT TELEFON FROM TBL_CARI_TELEFON WITH (NOLOCK)) AND
		CARIKODU NOT IN (SELECT CARIKODU FROM TBL_CARI_TELEFON WITH (NOLOCK)) 


		DROP TABLE #TMP
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_TELEFON TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	IF ISNULL((SELECT COUNT(*) FROM TBL_CARI_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END

COMMIT TRAN

DROP TABLE #TEMPFILE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_LOG_CLEAR]
AS
	BEGIN TRY
		ALTER DATABASE BARPOS SET RECOVERY SIMPLE WITH NO_WAIT
		DBCC SHRINKFILE(BARPOS_Log, 1)
		ALTER DATABASE BARPOS SET RECOVERY FULL WITH NO_WAIT
	END TRY
	BEGIN CATCH
	END CATCH
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_HEDIYE_CEK]
	@ID	INT = NULL
AS
	SELECT @ID = MAX(ID) FROM TBL_HEDIYE_CEK WITH (NOLOCK)
	
	IF NOT EXISTS(SELECT TOP 1 ID FROM TBL_HEDIYE_CEK WITH (NOLOCK))
	BEGIN
		SELECT 
			CONVERT(INT, 1) AS ID,
			CONVERT(VARCHAR(10), '001') AS KASANO,
			CONVERT(VARCHAR(20), '122022021134334') AS CEKNO,
			CONVERT(VARCHAR(50), 'MEHMET SOYLEMEZOGLU') AS CARIADI,
			CONVERT(FLOAT, 22.50) AS TUTAR,
			GETDATE() AS TARIH,
			CONVERT(VARCHAR(50), 'SEDA HAKYEMEZ') AS KASIYERADI
	END
	ELSE
		SELECT 
			ID,
			KASANO,
			CEKNO,
			CARIADI,
			TUTAR,
			TARIH,
			KASIYERADI
		FROM TBL_HEDIYE_CEK WITH (NOLOCK)
		WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_HEDIYE_CEK_INSERT]
	@KASANO		VARCHAR(10),
	@CEKNO		VARCHAR(20),
	@CARIADI	VARCHAR(50),
	@TUTAR		FLOAT,
	@TARIH		DATETIME,
	@KASIYERADI	VARCHAR(50)
AS

	INSERT INTO TBL_HEDIYE_CEK(KASANO, CEKNO, CARIADI, TUTAR, TARIH, KASIYERADI)
	SELECT @KASANO, @CEKNO, @CARIADI, @TUTAR, @TARIH, @KASIYERADI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_FIS_GRUP_DETAY]
	@ID	INT = NULL,
	@DETAYIDS VARCHAR(MAX) = NULL
AS
	IF @DETAYIDS <> ''
	BEGIN
		SELECT 
			MIN(SATIRNO) AS SATIRNO, 
			PLUNO, 
			BARKOD, 
			STOKADI, 
			KDV, 
			DEPARTMAN, 
			BIRIM, 
			SUM(MIKTAR) AS MIKTAR, 
			MAX(FIYAT) AS FIYAT, 
			SUM(TUTAR-ABS(INDTUTAR)) AS TUTAR,
			SUM(CASE WHEN TIP = 'IPT' THEN DOVIZTUTARI - TUTAR ELSE INDTUTAR END) AS INDTUTAR
		FROM TBL_FIS_DETAY WITH (NOLOCK)
		WHERE ID IN (SELECT CODE FROM dbo.GETPARAMS(@DETAYIDS))
		GROUP BY PLUNO, BARKOD, STOKADI, KDV, DEPARTMAN, BIRIM
		HAVING SUM(MIKTAR) > 0
		ORDER BY MIN(SATIRNO)
		
		RETURN
	END

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

	SELECT 
		MIN(SATIRNO) AS SATIRNO, 
		PLUNO, 
		BARKOD, 
		STOKADI, 
		KDV, 
		DEPARTMAN, 
		BIRIM, 
		SUM(MIKTAR) AS MIKTAR, 
		MAX(FIYAT) AS FIYAT, 
		SUM(TUTAR-ABS(INDTUTAR)) AS TUTAR,
		SUM(CASE WHEN TIP = 'IPT' THEN DOVIZTUTARI - TUTAR ELSE INDTUTAR END) AS INDTUTAR
	FROM TBL_FIS_DETAY WITH (NOLOCK)
	WHERE FISID = @ID
	GROUP BY PLUNO, BARKOD, STOKADI, KDV, DEPARTMAN, BIRIM
	HAVING SUM(MIKTAR) > 0
	ORDER BY MIN(SATIRNO)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_FIS_SIPARIS_BILGILERI]
	@ID	INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

	SELECT * FROM TBL_FIS_SIPARIS_BILGILERI WITH (NOLOCK)
	WHERE FISID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_FIS_SIPARIS_BILGILERI_INSERT]
	@FISID				INT ,
	@SIPARISID			INT ,
	@DELIVERYTIME		DATETIME,
	@PLATFORMTYPE		TINYINT,
	@CUSTOMERNAME		VARCHAR(255),
	@CUSTOMERPHONE		VARCHAR(255),
	@ORDERTOTAL			MONEY,
	@ADDRESS			VARCHAR(MAX),
	@ADDRESSDESCRIPTION VARCHAR(MAX),
	@ORDERNOTE			VARCHAR(MAX),
	@KURYEADI			VARCHAR(50)
AS

	INSERT INTO TBL_FIS_SIPARIS_BILGILERI(
											FISID				,
											SIPARISID			,
											DELIVERYTIME		,
											PLATFORMTYPE		,
											CUSTOMERNAME		,
											CUSTOMERPHONE		,
											ORDERTOTAL			,
											ADDRESS				,
											ADDRESSDESCRIPTION	,
											ORDERNOTE			,
											KURYEADI				
										)
	SELECT 
		@FISID				,
		@SIPARISID			,
		@DELIVERYTIME		,
		@PLATFORMTYPE		,
		@CUSTOMERNAME		,
		@CUSTOMERPHONE		,
		@ORDERTOTAL			,
		@ADDRESS			,
		@ADDRESSDESCRIPTION ,
		@ORDERNOTE			,
		@KURYEADI				

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_STOK_SATIS_ADET_REYON_REPORT]
	@KASANO		INT = NULL,
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL
AS

	IF @KASANO IS NULL
	BEGIN
		SET @KASANO = 1
		SET @ILKTARIH = '07/25/2016 00:00:01'
		SET @SONTARIH = '07/25/2050 23:59:59'
	END

SELECT
	S.REYONADI,
	SUM(
			CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END  *
			CASE WHEN D.TIP = 'IPT' THEN -1 ELSE 1 END *
			ABS(D.MIKTAR)
		) AS MIKTAR,
	SUM(
		CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END  *
		CASE WHEN D.TIP = 'IPT' THEN -1 ELSE 1 END *
		ABS(D.TUTAR)
		) AS TUTAR
INTO #TMPTBL FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
	INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
WHERE
	M.KASANO	= @KASANO AND
	M.TARIH	>= @ILKTARIH AND
	M.TARIH	<= @SONTARIH AND
	M.TIP IN (0,1,2) AND
	D.TIP IN ('SAT', 'IPT')
GROUP BY S.REYONADI
ORDER BY SUM(D.TUTAR) DESC

SELECT @ILKTARIH AS ILKTARIH, @SONTARIH AS SONTARIH, REYONADI, MIKTAR, CASE WHEN MIKTAR = 0 THEN 0 ELSE TUTAR / MIKTAR END AS FIYAT, TUTAR
FROM #TMPTBL
WHERE MIKTAR <> 0

DROP TABLE #TMPTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_TARIH_KONTROL]
AS
	SET NOCOUNT ON

	DECLARE 
		@SONFISTARIHI DATETIME, 
		@PCTARIH DATETIME
	
	SET @PCTARIH = GETDATE()

	SELECT @SONFISTARIHI = MAX(TARIH) FROM TBL_FIS_MAIN WITH (NOLOCK)

	SET @SONFISTARIHI = ISNULL(@SONFISTARIHI, @PCTARIH)

	IF @SONFISTARIHI > @PCTARIH
		RAISERROR('TARİH VE SAATİ KONTROL EDİNİZ.!',16,1)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_EFATURA_INSERT]
	@ALIAS		VARCHAR(MAX), 
	@CREATEDATE	DATETIME, 
	@IDENTIFIER	VARCHAR(MAX), 
	@AKTIF		BIT, 
	@TITLE		VARCHAR(MAX), 
	@TYPE		VARCHAR(MAX), 
	@UPDATEDATE	DATETIME = NULL
AS
		
	IF (EXISTS(SELECT TOP 1 ID FROM TBL_CARI_EFATURA WITH (NOLOCK) WHERE IDENTIFIER = @IDENTIFIER))
	BEGIN
		DECLARE @ID INT
		SELECT @ID = ID FROM TBL_CARI_EFATURA WITH (NOLOCK) WHERE IDENTIFIER = @IDENTIFIER AND ALIAS = @ALIAS
		IF @ID IS NOT NULL
		BEGIN
			UPDATE TBL_CARI_EFATURA
			SET 
				CREATEDATE	= @CREATEDATE,
				IDENTIFIER	= @IDENTIFIER,
				AKTIF		= @AKTIF,
				TITLE		= @TITLE,
				TYPE		= @TYPE,
				UPDATEDATE	= ISNULL(@UPDATEDATE, @CREATEDATE)
			WHERE ID = @ID
		END
		ELSE
			INSERT INTO TBL_CARI_EFATURA(ALIAS, CREATEDATE, IDENTIFIER, AKTIF, TITLE, TYPE, UPDATEDATE)
			SELECT @ALIAS, @CREATEDATE, @IDENTIFIER, @AKTIF, @TITLE, @TYPE, ISNULL(@UPDATEDATE, @CREATEDATE)

	END
	ELSE
		INSERT INTO TBL_CARI_EFATURA(ALIAS, CREATEDATE, IDENTIFIER, AKTIF, TITLE, TYPE, UPDATEDATE)
		SELECT @ALIAS, @CREATEDATE, @IDENTIFIER, @AKTIF, @TITLE, @TYPE, ISNULL(@UPDATEDATE, @CREATEDATE)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_ODEME_KONTROL_LIST]
	@KDVORANLARI VARCHAR(MAX) = NULL,
	@STOKADI VARCHAR(50) = NULL
AS
	SELECT STOKADI
	FROM TBL_BEKLETME_DETAY WITH (NOLOCK) 
	WHERE 
		FISID IN ( SELECT ID FROM TBL_BEKLETME_MAIN WHERE ISBEKLETME = 0) AND 
		KDV IN (SELECT CODE FROM dbo.GETPARAMS(@KDVORANLARI))
	GROUP BY STOKADI
	HAVING SUM(MIKTAR) > 0
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_PROMOSYON_INSERT]
	@FISID			INT, 
	@PROMOSYONTIPI	VARCHAR(3), 
	@INDYUZDE		FLOAT, 
	@INDTUTAR		FLOAT, 
	@ACIKLAMA		VARCHAR(MAX),
	@KREDINO		INT,
	@PLUNO			INT
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_PROMOSYON(FISID, PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, KREDINO, PLUNO)
	SELECT @FISID, @PROMOSYONTIPI, @INDYUZDE, @INDTUTAR, @ACIKLAMA, @KREDINO, @PLUNO
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_PROMOSYON_LIST]
	@FISID			INT 
AS
	SET NOCOUNT ON

	SELECT ID, FISID, PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, KREDINO, PLUNO FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
	WHERE FISID = @FISID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_ILCE_LIST]
	@ID			INT			= NULL,
	@ILID		INT			= NULL,
	@ILCEADI	VARCHAR(50)	= NULL
AS
	SET NOCOUNT ON

	SELECT	
		C.ID,
		C.ILID,
		I.ILADI,
		C.ILCEADI
	FROM TBL_ILCE C WITH (NOLOCK) 
		INNER JOIN TBL_IL I WITH (NOLOCK) ON I.ID = C.ILID
	WHERE
		C.ID = ISNULL(@ID, C.ID) AND 
		C.ILID = ISNULL(@ILID, C.ILID) AND
		C.ILCEADI LIKE ISNULL('%'+@ILCEADI+'%', C.ILCEADI) 
	ORDER BY C.ILCEADI ASC

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IL_LIST]
	@ID			INT			= NULL,
	@BOLGEID	INT			= NULL,
	@ILADI		VARCHAR(50)	= NULL
AS
	SET NOCOUNT ON

	SELECT	
		I.ID,
		I.BOLGEID,
		B.BOLGEADI,
		I.ILADI
	FROM TBL_IL I WITH (NOLOCK) 
		INNER JOIN TBL_BOLGE B WITH (NOLOCK) ON B.ID = I.BOLGEID
	WHERE
		I.ID = ISNULL(@ID, I.ID) AND 
		I.BOLGEID = ISNULL(@BOLGEID, I.BOLGEID) AND
		I.ILADI LIKE ISNULL('%'+@ILADI+'%', I.ILADI) 
	ORDER BY I.ILADI ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_BOLGE_LIST]
	@ID			INT			= NULL,
	@BOLGEADI	VARCHAR(50)	= NULL
AS
	SET NOCOUNT ON

	SELECT	
		ID,
		BOLGEADI
	FROM TBL_BOLGE WITH (NOLOCK)
	WHERE 
		ID = ISNULL(@ID, ID) AND
		BOLGEADI LIKE ISNULL('%'+@BOLGEADI+'%', BOLGEADI)
	ORDER BY BOLGEADI 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_FIS_LOG_LIST]
	@FISID			INT = NULL
AS
	SET NOCOUNT ON
	IF @FISID IS NULL
		SELECT @FISID = MIN(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

	SELECT ACIKLAMA FROM TBL_FIS_LOG WITH (NOLOCK)
	WHERE FISID = @FISID

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_BEKLETME_MAIN_BROWSE]
	@BELGEKODU	VARCHAR(20) = NULL,
	@TARIH		DATETIME = NULL,
	@CARIADI	VARCHAR(50) = NULL,
	@TUTAR		FLOAT = NULL
AS
	SELECT
		B.ID,
		B.BELGEKODU,
		B.TARIH,
		B.CARIADI,
		B.TUTAR
	FROM TBL_BEKLETME_MAIN B WITH (NOLOCK)
	WHERE
		B.ISBEKLETME = 1 AND
		B.BELGEKODU LIKE ISNULL('%'+@BELGEKODU+'%', B.BELGEKODU) AND
		B.TARIH = ISNULL(@TARIH, B.TARIH) AND
		B.CARIADI LIKE ISNULL('%'+@CARIADI+'%', B.CARIADI) AND
		B.TUTAR = ISNULL(@TUTAR, B.TUTAR)
	ORDER BY TARIH DESC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_FIS_ODEME]  
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)


	SELECT O.FISID, O.KREDINO, O.KREDITIPI, SUM(ISNULL(CASE WHEN O.TUTAR = 0 THEN DOVIZTUTARI ELSE O.TUTAR END,0)) AS TUTAR, ISTICKET FROM TBL_FIS_ODEME O WITH (NOLOCK)
	WHERE O.FISID = @ID
	GROUP BY O.FISID, O.KREDINO, O.KREDITIPI, ISTICKET
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_FIS_ODEME_INSERT]
	@FISID			INT,
	@KREDINO		INT,
	@KREDITIPI		VARCHAR(50),
	@TUTAR			FLOAT,
	@DOVIZKODU		VARCHAR(10),
	@DOVIZKURU		FLOAT,
	@DOVIZTUTARI	FLOAT,
	@ISTICKET		BIT
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_ODEME(FISID, KREDINO, KREDITIPI, TUTAR, DOVIZKODU, DOVIZKURU, DOVIZTUTARI, ISTICKET)
	SELECT @FISID, @KREDINO, @KREDITIPI, @TUTAR, @DOVIZKODU, @DOVIZKURU, @DOVIZTUTARI, @ISTICKET
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_MAIN_INSERT]
	@TARIH			DATETIME,
	@KASANO			INT,
	@KASIYERKODU	VARCHAR(100),
	@KASIYERADI		VARCHAR(50)
AS
	
	INSERT INTO TBL_KASA_TAKIP_FIS_MAIN(TARIH, KASANO, KASIYERKODU, KASIYERADI)
	SELECT @TARIH, @KASANO, @KASIYERKODU, @KASIYERADI
	
	RETURN ISNULL((SELECT MAX(ID) FROM TBL_KASA_TAKIP_FIS_MAIN WITH (NOLOCK)),0)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_DETAY_INSERT]
	@BELGEID	INT,
	@ACIKLAMA	VARCHAR(100),
	@TIP		INT,
	@TIPNO		INT,
	@ADET		INT,
	@TUTAR		FLOAT
AS
	INSERT INTO TBL_KASA_TAKIP_FIS_DETAY(BELGEID, ACIKLAMA, TIP, TIPNO, ADET, TUTAR)
	SELECT @BELGEID, @ACIKLAMA, @TIP, @TIPNO, @ADET, @TUTAR
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_DETAY_LIST]
	@BELGEID INT = NULL
AS
	IF @BELGEID IS NULL 
		SELECT @BELGEID = MAX(ID) FROM TBL_KASA_TAKIP_FIS_MAIN WITH (NOLOCK)

	SELECT * FROM TBL_KASA_TAKIP_FIS_DETAY WITH (NOLOCK)
	WHERE BELGEID = @BELGEID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KASA_TAKIP_FIS_MAIN_LIST]
	@BELGEID INT = NULL
AS
	IF @BELGEID IS NULL 
		SELECT @BELGEID = MAX(ID) FROM TBL_KASA_TAKIP_FIS_MAIN WITH (NOLOCK)

	SELECT * FROM TBL_KASA_TAKIP_FIS_MAIN WITH (NOLOCK)
	WHERE ID = @BELGEID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_TALEP_MAIN_LIST]
AS
	SELECT ID, SIPARISID, BELGEKODU, CARIADI FROM TBL_SIPARIS_TALEP_MAIN WITH (NOLOCK)
	ORDER BY SIPARISID DESC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_TALEP_MAIN_INSERT]
	@SIPARISID	INT,
	@BELGEKODU	VARCHAR(20),
	@CARIADI	VARCHAR(255)
AS
	INSERT INTO TBL_SIPARIS_TALEP_MAIN(SIPARISID, BELGEKODU, CARIADI)
	SELECT @SIPARISID, @BELGEKODU, @CARIADI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_CALLER_ID_LIST]
	@SONKONTROLTARIHI DATETIME
AS
	SELECT TOP 1 * FROM TBL_CALLER_ID WITH (NOLOCK)
	WHERE TARIH > @SONKONTROLTARIHI
	ORDER BY ID DESC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_CALLER_ID_INSERT]
	@TELEFONNUMARASI VARCHAR(20)
AS
	INSERT INTO TBL_CALLER_ID(TELEFONNUMARASI, TARIH)
	SELECT @TELEFONNUMARASI, GETDATE()
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SMS_KONTROL_LIST]
	@TELEFON	VARCHAR(20)
AS
	SELECT SMSSIFRE FROM TBL_SMS_KONTROL WITH (NOLOCK)
	WHERE TELEFON = @TELEFON
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SMS_KONTROL_INSERT]
	@TELEFON	VARCHAR(20),
	@SMSSIFRE	VARCHAR(6)
AS
	IF EXISTS(SELECT TOP 1 1 FROM TBL_SMS_KONTROL WITH (NOLOCK) WHERE TELEFON = @TELEFON)
		UPDATE TBL_SMS_KONTROL
		SET SMSSIFRE = @SMSSIFRE,
			CREATEDATE = GETDATE()
		WHERE TELEFON = @TELEFON
	ELSE
		INSERT INTO TBL_SMS_KONTROL(TELEFON, SMSSIFRE, CREATEDATE)
		SELECT @TELEFON, @SMSSIFRE, GETDATE()
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_EFATURA_FILE]
AS
DECLARE 
	@DATA NVARCHAR(1000)

DECLARE CURR CURSOR FAST_FORWARD FOR
SELECT DATA FROM TBL_IMPORT_FILE (NOLOCK)
OPEN CURR

FETCH NEXT FROM CURR
INTO @DATA

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @DATA = 'INSERT INTO TBL_CARI_EFATURA(ALIAS, CREATEDATE, IDENTIFIER, AKTIF, TITLE, TYPE, UPDATEDATE) SELECT '+@DATA
	
	EXECUTE sp_ExecuteSQL @DATA
	
	FETCH NEXT FROM CURR
	INTO @DATA
END

CLOSE CURR
DEALLOCATE CURR
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_STOK_SATIS_LIST]
	@TELEFON	VARCHAR(20) = '',
	@BARKOD		VARCHAR(20) = NULL,
	@STOKADI	VARCHAR(50) = NULL
AS

SELECT 
	 S.PLUNO,
	 CONVERT(VARCHAR(20), '') AS BARKOD,
	 CONVERT(VARCHAR(50), '') AS STOKADI,
	 SUM(D.MIKTAR) AS MIKTAR,
	 SUM(D.TUTAR) AS TUTAR
INTO #STOK FROM TBL_SIPARIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_SIPARIS M WITH (NOLOCK) ON M.ID = D.SIPARISID
	INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
WHERE 
	M.DURUM = 3 AND 
	M.TELEFON = @TELEFON AND 
	S.BARKOD = ISNULL(@BARKOD, S.BARKOD) AND 
	S.STOKADI LIKE ISNULL('%'+@STOKADI+'%', S.STOKADI) 
GROUP BY S.PLUNO

UPDATE #STOK
SET BARKOD = M.BARKOD,
	STOKADI = M.STOKADI
FROM #STOK S
	INNER JOIN TBL_STOK_MAIN M WITH (NOLOCK) ON M.PLUNO = S.PLUNO

SELECT * FROM #STOK
ORDER BY MIKTAR DESC, STOKADI 

DROP TABLE #STOK
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_MESAJ_LIST]
	@TELEFON VARCHAR(20)
AS
	SELECT * FROM TBL_MESAJ WITH (NOLOCK)
	WHERE 
		KIMDEN = @TELEFON OR 
		KIME = @TELEFON
	ORDER BY ID ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_HAZIR_MESAJ_LIST]
	@KISAYOL VARCHAR(1) = NULL
AS
	SELECT * FROM TBL_HAZIR_MESAJ WITH (NOLOCK)
	WHERE KISAYOL = ISNULL(@KISAYOL, KISAYOL)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_HAZIR_MESAJ_DELETE]
	@ID INT 
AS
	DELETE FROM TBL_HAZIR_MESAJ
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_HAZIR_MESAJ_INSERT_UPDATE]
	@ID		 INT = NULL,
	@KISAYOL VARCHAR(1),
	@MESAJ	 VARCHAR(MAX)
AS
	SET NOCOUNT ON
	DECLARE @ERRORMESSAGE NVARCHAR(MAX)
	
	IF @ID IS NULL
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM TBL_HAZIR_MESAJ WHERE KISAYOL = @KISAYOL)
		BEGIN
			SET @ERRORMESSAGE = 'KISAYOL DAHA ÖNCE TANIMLANMIŞ'
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END

		INSERT INTO TBL_HAZIR_MESAJ(KISAYOL, MESAJ)
		SELECT @KISAYOL, @MESAJ
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM TBL_HAZIR_MESAJ WHERE ID <> @ID AND KISAYOL = @KISAYOL)
		BEGIN
			SET @ERRORMESSAGE = 'KISAYOL DAHA ÖNCE TANIMLANMIŞ'
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END

		UPDATE TBL_HAZIR_MESAJ
		SET KISAYOL = @KISAYOL ,
			MESAJ = @MESAJ
		WHERE ID = @ID
	END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SEPET_DELETE]
	@TELEFON VARCHAR(20)
AS
	DELETE FROM TBL_SEPET
	WHERE TELEFON = @TELEFON
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SEPET_LIST]
	@TELEFON VARCHAR(20)
AS
	SELECT S.*, M.STOKADI FROM TBL_SEPET S WITH (NOLOCK)
		INNER JOIN TBL_STOK_MAIN M WITH (NOLOCK) ON M.BARKOD = S.BARKOD
	WHERE S.TELEFON = @TELEFON
	ORDER BY S.ID ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SEPET_INSERT]
	@SEPETID VARCHAR(50),
	@TELEFON VARCHAR(20),
	@BARKOD VARCHAR(20),
	@MIKTAR FLOAT,
	@FIYAT FLOAT,
	@TUTAR FLOAT,
	@BIRIM VARCHAR(10)
AS
	INSERT INTO TBL_SEPET(SEPETID, TELEFON, BARKOD, MIKTAR, BIRIM, FIYAT, TUTAR, TARIH)
	SELECT @SEPETID, @TELEFON, @BARKOD, @MIKTAR, @BIRIM, @FIYAT, @TUTAR, GETDATE()
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_DETAY_INSERT]
	@SIPARISID	INT,
	@BARKOD		VARCHAR(20),
	@URUNADI	VARCHAR(255),
	@MIKTAR		FLOAT,
	@BIRIM		VARCHAR(10),
	@FIYAT		FLOAT,
	@TUTAR		FLOAT
AS
	SET NOCOUNT ON
	
	INSERT INTO TBL_SIPARIS_DETAY(SIPARISID, BARKOD, URUNADI, MIKTAR, BIRIM, FIYAT, TUTAR)
	SELECT @SIPARISID, @BARKOD, @URUNADI, @MIKTAR, @BIRIM, @FIYAT, @TUTAR
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_DETAY_LIST]
	@SIPARISID	INT
AS
	SET NOCOUNT ON
	
	SELECT * FROM TBL_SIPARIS_DETAY (NOLOCK)
	WHERE SIPARISID = @SIPARISID
	ORDER BY ID ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_SIPARIS]
	@ID INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_SIPARIS WITH (NOLOCK)
	
	SET NOCOUNT ON

	SELECT 
		*, 
		CASE DURUM WHEN 0 THEN 'BEKLİYOR' WHEN 1 THEN 'HAZIRLANIYOR' WHEN 2 THEN 'YOLA ÇIKTI' WHEN 3 THEN 'TESLİM EDİLDİ' WHEN 4 THEN 'İPTAL EDİLDİ' ELSE 'BİLİNMİYOR' END AS DURUMACIKLAMA,
		CASE ODEMESEKLI WHEN 0 THEN 'NAKİT ÖDEME' WHEN 1 THEN 'KREDİ KARTI' ELSE 'ONLINE ODEME' END AS ODEMESEKLIACIKLAMA
	FROM TBL_SIPARIS WITH (NOLOCK)
	WHERE 
		ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_SIPARIS_DETAY]
	@ID	INT = NULL
AS
	SET NOCOUNT ON
	
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_SIPARIS WITH (NOLOCK)

	SELECT * FROM TBL_SIPARIS_DETAY (NOLOCK)
	WHERE SIPARISID = @ID
	ORDER BY ID ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_STOK_SIPARIS_LIST]
	@SIPARISID INT
AS
	SELECT
		S.BARKOD,
		S.STOKADI,
		S.BIRIM,
		S.FIYAT,
		P.MIKTAR,
		P.MIKTAR * S.FIYAT AS TUTAR
	FROM TBL_STOK_MAIN S WITH (NOLOCK)
		INNER JOIN TBL_SIPARIS_DETAY P WITH (NOLOCK) ON P.BARKOD = S.BARKOD
	WHERE P.SIPARISID = @SIPARISID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SUBE_INSERT_UPDATE]
	@ID			INT = NULL,
	@MERKEZ		BIT,
	@SUBEKODU	VARCHAR(20),
	@YETKILI	VARCHAR(20),
	@TELEFON	VARCHAR(20)
AS
	SET NOCOUNT ON
	DECLARE @ERRORMESSAGE NVARCHAR(MAX)
	
	IF @ID IS NULL
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM TBL_SUBE WHERE SUBEKODU = @SUBEKODU)
		BEGIN
			SET @ERRORMESSAGE = 'SUBE DAHA ÖNCE TANIMLANMIŞ'
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END

		INSERT INTO TBL_SUBE(MERKEZ, SUBEKODU, YETKILI, TELEFON)
		SELECT @MERKEZ, @SUBEKODU, @YETKILI, @TELEFON
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM TBL_SUBE WHERE ID <> @ID AND SUBEKODU = @SUBEKODU)
		BEGIN
			SET @ERRORMESSAGE = 'SUBE DAHA ÖNCE TANIMLANMIŞ'
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END

		UPDATE TBL_SUBE
		SET MERKEZ = @MERKEZ,
			SUBEKODU = @SUBEKODU ,
			YETKILI = @YETKILI,
			TELEFON = @TELEFON
		WHERE ID = @ID
	END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SUBE_DELETE]
	@ID INT 
AS
	DELETE FROM TBL_SUBE
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SUBE_LIST]
	@SUBEKODU VARCHAR(20) = NULL
AS
		SELECT 
			SUB.SUBEKODU,
			SUM(CASE S.DURUM WHEN 3 THEN TUTAR ELSE 0 END) AS CIROTUTARI
		INTO #CIRO FROM TBL_SIPARIS S WITH (NOLOCK)
			INNER JOIN TBL_CARI_TELEFON T WITH (NOLOCK) ON T.TELEFON = S.TELEFON
			INNER JOIN TBL_SUBE_CARI B WITH (NOLOCK) ON B.CARIKODU = T.CARIKODU 
			INNER JOIN TBL_SUBE SUB WITH (NOLOCK) ON SUB.ID = B.SUBEID
		WHERE 
			S.TARIH >= CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 112)) AND
			S.TARIH < CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE()+1, 112)) 
		GROUP BY SUB.SUBEKODU

	SELECT S.*, ISNULL(C.CIROTUTARI,0) AS CIRO FROM TBL_SUBE S WITH (NOLOCK)
		LEFT JOIN #CIRO C ON C.SUBEKODU = S.SUBEKODU
	WHERE S.SUBEKODU = ISNULL(@SUBEKODU, S.SUBEKODU)

	DROP TABLE #CIRO
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_ADRES_DELETE]
	@ID INT 
AS
	SET NOCOUNT ON
	
	IF ((EXISTS(SELECT TOP 1 1 FROM TBL_CARI_ADRES WHERE ID = @ID AND AKTIF = 1)))
	BEGIN
		RAISERROR('AKTİF ADRES BAŞKA ADRES AKTİF EDİLMEDEN SİLİNEMEZ.!',16,1)
		RETURN
	END
	
	DELETE FROM TBL_CARI_ADRES
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_ADRES_LIST]
	@CARIKODU VARCHAR(20) = NULL
AS
	SELECT ID, CARIKODU, AKTIF, ADRES, LATITUDE, LONGITUDE FROM TBL_CARI_ADRES WITH (NOLOCK)
	WHERE CARIKODU = ISNULL(@CARIKODU, CARIKODU)
	ORDER BY AKTIF DESC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_DASHBOARD]
	@SUBEKODU VARCHAR(20) = NULL
AS
	IF ISNULL(@SUBEKODU,'') <> ''
		SELECT 
			SUM(CASE S.DURUM WHEN 0 THEN 1 WHEN 1 THEN 1 ELSE 0 END) AS HAZIRLANIYORADET,
			SUM(CASE S.DURUM WHEN 0 THEN TUTAR WHEN 1 THEN TUTAR ELSE 0 END) AS HAZIRLANIYORTUTAR,
			SUM(CASE S.DURUM WHEN 2 THEN 1 ELSE 0 END) AS YOLDAADET,
			SUM(CASE S.DURUM WHEN 2 THEN TUTAR ELSE 0 END) AS YOLDATUTAR,
			SUM(CASE S.DURUM WHEN 3 THEN 1 ELSE 0 END) AS TESLIMADET,
			SUM(CASE S.DURUM WHEN 3 THEN TUTAR ELSE 0 END) AS TESLIMTUTAR,
			SUM(CASE S.DURUM WHEN 4 THEN 1 ELSE 0 END) AS IPTALADET,
			SUM(CASE S.DURUM WHEN 4 THEN TUTAR ELSE 0 END) AS IPTALTUTAR
		FROM TBL_SIPARIS S WITH (NOLOCK)
			INNER JOIN TBL_CARI_TELEFON T WITH (NOLOCK) ON T.TELEFON = S.TELEFON
			INNER JOIN TBL_SUBE_CARI B WITH (NOLOCK) ON B.CARIKODU = T.CARIKODU 
			INNER JOIN TBL_SUBE SUB WITH (NOLOCK) ON SUB.ID = B.SUBEID
		WHERE 
			SUB.SUBEKODU = @SUBEKODU AND
			S.TARIH >= CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 112)) AND
			S.TARIH < CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE()+1, 112)) 
	ELSE
		SELECT 
			SUM(CASE DURUM WHEN 0 THEN 1 WHEN 1 THEN 1 ELSE 0 END) AS HAZIRLANIYORADET,
			SUM(CASE DURUM WHEN 0 THEN TUTAR WHEN 1 THEN TUTAR ELSE 0 END) AS HAZIRLANIYORTUTAR,
			SUM(CASE DURUM WHEN 2 THEN 1 ELSE 0 END) AS YOLDAADET,
			SUM(CASE DURUM WHEN 2 THEN TUTAR ELSE 0 END) AS YOLDATUTAR,
			SUM(CASE DURUM WHEN 3 THEN 1 ELSE 0 END) AS TESLIMADET,
			SUM(CASE DURUM WHEN 3 THEN TUTAR ELSE 0 END) AS TESLIMTUTAR,
			SUM(CASE DURUM WHEN 4 THEN 1 ELSE 0 END) AS IPTALADET,
			SUM(CASE DURUM WHEN 4 THEN TUTAR ELSE 0 END) AS IPTALTUTAR
		FROM TBL_SIPARIS WITH (NOLOCK)
		WHERE 
			TARIH >= CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 112)) AND
			TARIH < CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE()+1, 112)) 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_MESAJ_INSERT]
	@MESAJID	VARCHAR(50),
	@KIMDEN		VARCHAR(20),
	@KIME		VARCHAR(20),
	@MESAJ		VARCHAR(MAX),
	@DURUM		TINYINT,
	@TARIH		DATETIME
AS
	SET NOCOUNT ON

	IF NOT EXISTS(SELECT TOP 1 1 FROM TBL_MESAJ WITH (NOLOCK) WHERE MESAJID = @MESAJID)
		INSERT INTO TBL_MESAJ(MESAJID, KIMDEN, KIME, MESAJ, DURUM, TARIH)
		SELECT @MESAJID, @KIMDEN, @KIME, @MESAJ, @DURUM, @TARIH
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_ADRES_INSERT_UPDATE]
	@ID			INT = NULL,
	@CARIKODU	VARCHAR(20),
	@AKTIF		BIT,
	@ADRES		VARCHAR(1000),
	@LATITUDE	VARCHAR(20),
	@LONGITUDE	VARCHAR(20)
AS
	SET NOCOUNT ON

	DECLARE @ERRORMESSAGE NVARCHAR(MAX)
	
	IF @ID IS NULL
	BEGIN
		IF (EXISTS(SELECT TOP 1 1 FROM TBL_CARI_ADRES WITH (NOLOCK) WHERE CARIKODU = @CARIKODU AND ADRES = @ADRES))
			RETURN

		IF @AKTIF = 1
			UPDATE TBL_CARI_ADRES
			SET AKTIF = 0
			WHERE CARIKODU  = @CARIKODU
		ELSE
			IF NOT EXISTS(SELECT TOP 1 1 FROM TBL_CARI_ADRES  WITH (NOLOCK) WHERE CARIKODU = @CARIKODU)
				SET @AKTIF = 1
		
		INSERT INTO TBL_CARI_ADRES(CARIKODU, AKTIF, ADRES, LATITUDE, LONGITUDE)
		SELECT @CARIKODU, @AKTIF, @ADRES, @LATITUDE, @LONGITUDE
	END
	ELSE
	BEGIN
		IF ((EXISTS(SELECT TOP 1 1 FROM TBL_CARI_ADRES  WITH (NOLOCK) WHERE ID = @ID AND AKTIF = 1)) AND (@AKTIF = 0))
		BEGIN
			SET @ERRORMESSAGE = 'AKTİF ADRES BAŞKA ADRES AKTİF EDİLMEDEN PASİFE ÇEKİLEMEZ.!'
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END
		ELSE IF @AKTIF = 1
		BEGIN
			UPDATE TBL_CARI_ADRES
			SET AKTIF = 0
			WHERE CARIKODU  = @CARIKODU
		END

		UPDATE TBL_CARI_ADRES
		SET AKTIF = @AKTIF,
			ADRES = @ADRES,
			LATITUDE = @LATITUDE,
			LONGITUDE = @LONGITUDE
		WHERE ID = @ID
	END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_MESAJ_UPDATE]
	@MESAJID	VARCHAR(50),
	@DURUM		TINYINT
AS
	SET NOCOUNT ON

	UPDATE TBL_MESAJ
	SET DURUM = CASE WHEN DURUM = 2 THEN DURUM ELSE @DURUM END
	WHERE MESAJID = @MESAJID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KURYE_INSERT_UPDATE]
	@ID			INT = NULL,
	@AKTIF		BIT,
	@KURYEADI	VARCHAR(50),
	@TELEFON	VARCHAR(20),
	@PRIMYUZDE	DECIMAL(4,2)
AS
	SET NOCOUNT ON
	DECLARE @ERRORMESSAGE NVARCHAR(MAX)
	
	IF @ID IS NULL
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM TBL_KURYE WITH (NOLOCK) WHERE KURYEADI = @KURYEADI)
		BEGIN
			SET @ERRORMESSAGE = 'KURYE DAHA ÖNCE TANIMLANMIŞ'
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END

		INSERT INTO TBL_KURYE(AKTIF, KURYEADI, TELEFON, PRIMYUZDE)
		SELECT @AKTIF, @KURYEADI, @TELEFON, @PRIMYUZDE
	END
	ELSE
	BEGIN
		IF EXISTS(SELECT TOP 1 1 FROM TBL_KURYE WHERE ID <> @ID AND KURYEADI = @KURYEADI)
		BEGIN
			SET @ERRORMESSAGE = 'KURYE DAHA ÖNCE TANIMLANMIŞ'
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END

		UPDATE TBL_KURYE
		SET 
			AKTIF = @AKTIF,
			KURYEADI = @KURYEADI ,
			TELEFON = @TELEFON,
			PRIMYUZDE = @PRIMYUZDE
		WHERE ID = @ID
	END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KURYE_DELETE]
	@ID INT 
AS
	DELETE FROM TBL_KURYE
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_KURYE_LIST]
AS
	SELECT * FROM TBL_KURYE WITH (NOLOCK)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_MESAJ_CARI_LIST]
	@TELEFON VARCHAR(20),
	@SUBEKODU VARCHAR(20) = NULL,
	@SEARCHSTRING VARCHAR(255) = NULL
AS
	CREATE TABLE #TMP(ISDELETE BIT, TELEFON VARCHAR(20), CARIKODU VARCHAR(20), CARIADI VARCHAR(255), OKUNMAMISMESAJSAYISI INT, SONMESAJTARIHI DATETIME, SIPARISDURUMU VARCHAR(1))
	
	IF RTRIM(LTRIM(ISNULL(@SEARCHSTRING,''))) = ''
		INSERT INTO #TMP(TELEFON, CARIKODU, CARIADI, OKUNMAMISMESAJSAYISI, SONMESAJTARIHI)
		SELECT 
			KIMDEN, 
			ISNULL(ISNULL(T.CARIKODU, C.CARIKODU), 'BİLİNMİYOR') AS CARIKODU, 
			ISNULL(ISNULL(T.CARIADI, C.CARIADI), 'BİLİNMİYOR') AS CARIADI, 
			SUM(CASE WHEN DURUM = 0 THEN 1 ELSE 0 END) AS OKUNMAMISMESAJSAYISI,
			MAX(TARIH) AS SONMESAJTARIHI
		FROM TBL_MESAJ M WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN T WITH (NOLOCK) ON T.TELEFON = M.KIMDEN
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = M.KIMDEN
		WHERE KIME = @TELEFON 
		GROUP BY KIMDEN, ISNULL(T.CARIKODU, C.CARIKODU), ISNULL(T.CARIADI, C.CARIADI)
	ELSE
		INSERT INTO #TMP(TELEFON, CARIKODU, CARIADI, OKUNMAMISMESAJSAYISI, SONMESAJTARIHI)
		SELECT 
			KIMDEN, 
			ISNULL(ISNULL(T.CARIKODU, C.CARIKODU), 'BİLİNMİYOR') AS CARIKODU, 
			ISNULL(ISNULL(T.CARIADI, C.CARIADI), 'BİLİNMİYOR') AS CARIADI, 
			SUM(CASE WHEN DURUM = 0 THEN 1 ELSE 0 END) AS OKUNMAMISMESAJSAYISI,
			MAX(TARIH) AS SONMESAJTARIHI
		FROM TBL_MESAJ M WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN T WITH (NOLOCK) ON T.TELEFON = M.KIMDEN
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = M.KIMDEN
		WHERE KIME = @TELEFON AND 
			(
				KIMDEN LIKE '%'+@SEARCHSTRING+'%' OR
				ISNULL(ISNULL(T.CARIADI, C.CARIADI), 'BİLİNMİYOR') LIKE '%'+@SEARCHSTRING+'%' 
			)
		GROUP BY KIMDEN, ISNULL(T.CARIKODU, C.CARIKODU), ISNULL(T.CARIADI, C.CARIADI)

	IF ISNULL(@SUBEKODU,'') <> ''
	BEGIN
		UPDATE #TMP 
		SET ISDELETE = 1

		UPDATE #TMP
		SET ISDELETE = 0
		FROM #TMP M
			INNER JOIN TBL_SUBE_CARI B WITH (NOLOCK) ON B.CARIKODU = M.CARIKODU 
			INNER JOIN TBL_SUBE SUB WITH (NOLOCK) ON SUB.ID = B.SUBEID
		WHERE SUBEKODU = @SUBEKODU

		DELETE FROM #TMP
		WHERE ISDELETE = 1
	END

	UPDATE #TMP
	SET SIPARISDURUMU = CASE WHEN S.TELEFON IS NULL THEN SIPARISDURUMU ELSE 'Y' END
	FROM #TMP T
		LEFT JOIN (
					SELECT TELEFON FROM TBL_SIPARIS WITH (NOLOCK)
					WHERE DURUM = 2
					GROUP BY TELEFON
				  ) AS S ON S.TELEFON = T.TELEFON

	UPDATE #TMP
	SET SIPARISDURUMU = CASE WHEN S.TELEFON IS NULL THEN SIPARISDURUMU ELSE 'H' END
	FROM #TMP T
		LEFT JOIN (
					SELECT TELEFON FROM TBL_SIPARIS WITH (NOLOCK)
					WHERE DURUM IN (0,1) 
					GROUP BY TELEFON
				  ) AS S ON S.TELEFON = T.TELEFON

	UPDATE #TMP
	SET SIPARISDURUMU = CASE WHEN S.TELEFON IS NULL THEN SIPARISDURUMU ELSE 'S' END
	FROM #TMP T
		LEFT JOIN (
					SELECT TELEFON FROM TBL_SEPET WITH (NOLOCK)
					GROUP BY TELEFON
				  ) AS S ON S.TELEFON = T.TELEFON

		
	SELECT * FROM #TMP
	ORDER BY SONMESAJTARIHI ASC

	DROP TABLE #TMP
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_UPDATE]
	@ID				INT,
	@DURUM			TINYINT = NULL,
	@KURYEADI		VARCHAR(50) = NULL,
	@ACIKLAMA		VARCHAR(MAX) = NULL,
	@KURYECAGIRILDI BIT = NULL,
	@ODEMESEKLI		TINYINT = NULL
AS
	SET NOCOUNT ON

	UPDATE TBL_SIPARIS
	SET DURUM = ISNULL(@DURUM, DURUM),
		KURYEADI = ISNULL(@KURYEADI, KURYEADI),
		KURYECAGIRILDI = ISNULL(@KURYECAGIRILDI, KURYECAGIRILDI),
		ACIKLAMA = ISNULL(@ACIKLAMA, ACIKLAMA),
		ODEMESEKLI = ISNULL(@ODEMESEKLI, ODEMESEKLI),
		DURUMTARIHI = CASE WHEN @DURUM IS NULL THEN DURUMTARIHI ELSE GETDATE() END
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_INSERT]
	@TIP			TINYINT,
	@TARIH			DATETIME,
	@TELEFON		VARCHAR(20),
	@ADSOYAD		VARCHAR(255),
	@ADRES			VARCHAR(1000),
	@ACIKLAMA		VARCHAR(MAX),
	@SEPETID		VARCHAR(50),
	@TUTAR			FLOAT,
	@ODEMESEKLI		TINYINT
AS
	SET NOCOUNT ON

	DECLARE @ID	INT

	INSERT INTO TBL_SIPARIS(TIP,TARIH,TELEFON,ADSOYAD,ADRES,ACIKLAMA,SEPETID,TUTAR, KURYECAGIRILDI, ODEMESEKLI, DURUM,DURUMTARIHI)
	SELECT @TIP, GETDATE(), @TELEFON, @ADSOYAD, @ADRES, @ACIKLAMA, @SEPETID, @TUTAR, 0, @ODEMESEKLI, 1, GETDATE()

	SELECT @ID = MAX(ID) FROM TBL_SIPARIS WITH (NOLOCK)

	RETURN @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_LIST]
	@ID INT = NULL,
	@TELEFON VARCHAR(20) = NULL,
	@SUBEKODU VARCHAR(20) = NULL
AS
	SET NOCOUNT ON

	IF ISNULL(@SUBEKODU, '') <> '' 
		SELECT 
			TOP 1000
			S.*, 
			CASE S.DURUM WHEN 0 THEN 'BEKLİYOR' WHEN 1 THEN 'HAZIRLANIYOR' WHEN 2 THEN 'YOLA ÇIKTI' WHEN 3 THEN 'TESLİM EDİLDİ' WHEN 4 THEN 'İPTAL EDİLDİ' ELSE 'BİLİNMİYOR' END AS DURUMACIKLAMA,
			CASE S.ODEMESEKLI WHEN 0 THEN 'NAKİT ÖDEME' WHEN 1 THEN 'KREDİ KARTI' ELSE 'ONLINE ODEME' END AS ODEMESEKLIACIKLAMA
		FROM TBL_SIPARIS S WITH (NOLOCK)
			INNER JOIN TBL_CARI_TELEFON T WITH (NOLOCK) ON T.TELEFON = S.TELEFON
			INNER JOIN TBL_SUBE_CARI B WITH (NOLOCK) ON B.CARIKODU = T.CARIKODU 
			INNER JOIN TBL_SUBE SUB WITH (NOLOCK) ON SUB.ID = B.SUBEID
		WHERE SUB.SUBEKODU = @SUBEKODU
		ORDER BY TARIH DESC
	ELSE
		SELECT 
			TOP 1000
			*, 
			CASE DURUM WHEN 0 THEN 'BEKLİYOR' WHEN 1 THEN 'HAZIRLANIYOR' WHEN 2 THEN 'YOLA ÇIKTI' WHEN 3 THEN 'TESLİM EDİLDİ' WHEN 4 THEN 'İPTAL EDİLDİ' ELSE 'BİLİNMİYOR' END AS DURUMACIKLAMA,
			CASE ODEMESEKLI WHEN 0 THEN 'NAKİT ÖDEME' WHEN 1 THEN 'KREDİ KARTI' ELSE 'ONLINE ODEME' END AS ODEMESEKLIACIKLAMA
		FROM TBL_SIPARIS WITH (NOLOCK)
		WHERE 
			ID = ISNULL(@ID, ID) AND 
			TELEFON = ISNULL(@TELEFON, TELEFON)
		ORDER BY TARIH DESC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_STOK_NOBONUS_LIST]
	@STOKADI VARCHAR(50) = NULL
AS
	SELECT STOKADI
	FROM TBL_BEKLETME_DETAY WITH (NOLOCK) 
	WHERE 
		FISID IN ( SELECT ID FROM TBL_BEKLETME_MAIN WHERE ISBEKLETME = 0) AND 
		PLUNO IN (
					SELECT PLUNO FROM TBL_STOK_MAIN WITH (NOLOCK)
					WHERE ISNULL(REYONADI,'') = 'NOBONUS' 
				)
	GROUP BY STOKADI
	HAVING SUM(MIKTAR) > 0
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_MAIN_BROWSE]
	@RECORDCOUNT	INT		= NULL,
	@CARIADI		VARCHAR(50)	= NULL,
	@CARIKODU		VARCHAR(20)	= NULL,
	@TELEFON		VARCHAR(20)	= NULL,
	@VERGINO		VARCHAR(20)	= NULL,
	@VERGIDAIRESI	VARCHAR(20)	= NULL
AS
	SET NOCOUNT ON;

	SET @RECORDCOUNT = ISNULL(@RECORDCOUNT, 1000000)

	SELECT
		TOP (@RECORDCOUNT)
		ID,
		CARIADI,
		CARIKODU,
		TELEFON,
		VERGIDAIRESI,
		VERGINO
	FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE
		CARIKODU		LIKE ISNULL('%'+@CARIKODU+'%'	 ,	CARIKODU)	AND
		CARIADI			LIKE ISNULL('%'+@CARIADI+'%'	 ,	CARIADI)	AND
		TELEFON			LIKE ISNULL('%'+@TELEFON+'%'	 ,	TELEFON)	AND
		VERGINO			LIKE ISNULL('%'+@VERGINO+'%'	 ,	VERGINO)	AND
		VERGIDAIRESI	LIKE ISNULL('%'+@VERGIDAIRESI+'%',	VERGIDAIRESI)	
	ORDER BY CARIADI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_HAREKET_IBM_LIST]
	@TARIH	SMALLDATETIME = '08/20/2018',
	@MAGAZANO VARCHAR(6) = '2048',
	@TARTIFLAG VARCHAR(MAX) = '2755,2955'
AS	
DECLARE 
	@FLAG1 VARCHAR(2) = '',
	@FLAG2 VARCHAR(2) = '',
	@FLAG3 VARCHAR(2) = ''

DECLARE @TBL TABLE (ID INT IDENTITY(1,1), FLAG VARCHAR(MAX))	

INSERT INTO @TBL(FLAG)
SELECT CODE FROM dbo.GETPARAMS(@TARTIFLAG)	

SELECT 
	@FLAG1 = SUBSTRING(CASE WHEN ID = 1 THEN FLAG ELSE @FLAG1 END,1,2),
	@FLAG2 = SUBSTRING(CASE WHEN ID = 2 THEN FLAG ELSE @FLAG2 END,1,2),
	@FLAG3 = SUBSTRING(CASE WHEN ID = 3 THEN FLAG ELSE @FLAG3 END,1,2) 
FROM @TBL

SET DATEFORMAT mdy; 

SET @MAGAZANO = dbo.SR(@MAGAZANO,6)

DECLARE
	@AY		INT,
	@YIL	INT,
	@GUN	INT

SELECT
	@GUN	= DATEPART(DD, @TARIH),
	@AY		= DATEPART(MM, @TARIH),
	@YIL	= DATEPART(YY, @TARIH)

CREATE TABLE #HRTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, BELGEID INT, ISIPTAL BIT, SATIRNO INT, DATA VARCHAR(MAX), TIP INT, TUTAR FLOAT, KDVTUTAR FLOAT, DEPARTMAN INT)

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT 0, 0, -1, 'SIGNATURE=GNDSALES.GDF', -1

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	ID,
	CASE WHEN TIP = 3 THEN 1 ELSE 0 END,
	0,
	'01 '+
	dbo.SR(CONVERT(VARCHAR, KASANO),6)+
	dbo.SR(CONVERT(VARCHAR, TARIH, 103),14)+
	dbo.SR(BELGEKODU,12)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, TARIH, 108),':',''),12)+
	@MAGAZANO+
	dbo.SR(KASIYERKODU, 8)+
	CONVERT(VARCHAR, CASE WHEN TIP < 3 THEN TIP ELSE 0 END)+
	CONVERT(VARCHAR, CASE WHEN TIP = 3 THEN 1 ELSE 0 END)+
	dbo.SL(BELGEKODU,10)+
	'0     '+
	'0     '+
	dbo.SR(CONVERT(VARCHAR,  D.ADET+ISNULL(O.ADET,0)+2),6)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, TUTAR),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, D.KDVTUTAR),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, ABS((TUTAR + ABS(INDTUTAR) - DETAYTOPLAM) + ABS(F.INDTUTAR)))),'.',','),15)+ --Belgeye Uygulanan Toplam İndirim
	dbo.SR(REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, ABS((TUTAR + ABS(INDTUTAR) - DETAYTOPLAM)))),'.',','),15)+ --Satırlara Uygulanan Toplam İndirim
	'0              0              0              0              '+
	dbo.SR(ISNULL(CARIKODU,''),24)+
	'0',
	0
FROM TBL_FIS_MAIN F WITH (NOLOCK)
	INNER JOIN 	(
					SELECT 
						FISID, 
						COUNT(D.ID) ADET, 
						SUM((CASE WHEN (KDV = 0) OR (F.TUTAR+ABS(F.INDTUTAR) = 0) THEN 0 ELSE ROUND((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / (F.TUTAR+ABS(F.INDTUTAR))) * (D.TUTAR + D.INDTUTAR))) - ((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / (F.TUTAR+ABS(F.INDTUTAR))) * (D.TUTAR + D.INDTUTAR))) / (1+(D.KDV/100.00))),2) END)) AS KDVTUTAR,
						ABS(SUM(D.TUTAR)) DETAYTOPLAM
					FROM TBL_FIS_DETAY D WITH (NOLOCK)
						INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = D.FISID
					GROUP BY FISID
				) D ON D.FISID = F.ID
	LEFT JOIN 	(SELECT FISID, COUNT(ID) ADET FROM TBL_FIS_ODEME WITH (NOLOCK) GROUP BY FISID) O ON O.FISID = F.ID

WHERE
	DATEPART(DD, TARIH) = @GUN AND
	DATEPART(MM, TARIH) = @AY AND
	DATEPART(YY, TARIH) = @YIL 

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP, TUTAR, KDVTUTAR, DEPARTMAN)
SELECT
	D.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	SATIRNO,
	'02 '+
	dbo.SR(CONVERT(VARCHAR, SATIRNO),6)+
	dbo.SR(CASE WHEN ISNULL(D.STOKKODU,'') = '' THEN BARKOD ELSE D.STOKKODU END,24)+
	CASE WHEN D.TIP = 'SAT' THEN '0' ELSE '1' END+
	dbo.SR(PLASIYERKODU,6)+
	dbo.SR(CONVERT(VARCHAR, DEPARTMAN-1),2)+
	dbo.SR(CONVERT(VARCHAR, KDV),3)+
	dbo.SR(
		CONVERT(VARCHAR, ABS(ROUND(
								CASE WHEN 
									BARKOD <> '' AND 
									SUBSTRING(BARKOD,1,2) = @FLAG1 OR   
									SUBSTRING(BARKOD,1,2) = @FLAG2 OR   
									SUBSTRING(BARKOD,1,2) = @FLAG3 
								THEN CONVERT(FLOAT,MIKTAR * 1000)
								ELSE CONVERT(FLOAT,MIKTAR) END,0)
				)),15)+
	CASE WHEN 
		BARKOD <> '' AND 
		SUBSTRING(BARKOD,1,2) = @FLAG1 OR   
		SUBSTRING(BARKOD,1,2) = @FLAG2 OR   
		SUBSTRING(BARKOD,1,2) = @FLAG3 
	THEN '1'
	ELSE '0' END+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(CONVERT(FLOAT, FIYAT))),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(CONVERT(FLOAT, D.TUTAR + D.INDTUTAR))),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(CONVERT(FLOAT, (CASE WHEN (KDV = 0) OR (F.TUTAR+ABS(F.INDTUTAR) = 0) THEN 0 ELSE ROUND((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / (F.TUTAR+ABS(F.INDTUTAR))) * (D.TUTAR + D.INDTUTAR))) - ((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / (F.TUTAR+ABS(F.INDTUTAR))) * (D.TUTAR + D.INDTUTAR))) / (1+(D.KDV/100.00))),2) END)))),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(CONVERT(FLOAT, D.INDTUTAR))),'.',','),15)+
	'0              0              0              0              '+
	'0'+
	dbo.SR(D.BARKOD, 24)+
	'0              0 0000                                      0           0           ',
	1,
	D.TUTAR + D.INDTUTAR,
	(CASE WHEN (KDV = 0) OR (F.TUTAR+ABS(F.INDTUTAR) = 0) THEN 0 ELSE ROUND((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / (F.TUTAR+ABS(F.INDTUTAR))) * (D.TUTAR + D.INDTUTAR))) - ((D.TUTAR - ABS(D.INDTUTAR) - ABS((F.INDTUTAR / (F.TUTAR+ABS(F.INDTUTAR))) * (D.TUTAR + D.INDTUTAR))) / (1+(D.KDV/100.00))),2) END),
	DEPARTMAN
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = D.FISID
WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE)	
	
INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	O.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	ROW_NUMBER() OVER(PARTITION BY O.FISID ORDER BY O.ID ASC) + H.MAXSATIRNO,
	'03 '+
	dbo.SR(CONVERT(VARCHAR, ROW_NUMBER() OVER(PARTITION BY O.FISID ORDER BY O.ID ASC)),6)+
	dbo.SR(CONVERT(VARCHAR, O.KREDINO),2)+
	'01'+--Ödeme + Normal Ödeme
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(CONVERT(FLOAT, O.TUTAR))),'.',','),15)+
	'0                                      00                                             0 ',
	2
FROM TBL_FIS_ODEME O WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = O.FISID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = O.FISID
	

CREATE TABLE #KDVTABLE(
						FISID INT, 
						SATIS1 FLOAT, SATIS2 FLOAT, SATIS3 FLOAT, SATIS4 FLOAT, SATIS5 FLOAT, 
						SATIS6 FLOAT, SATIS7 FLOAT, SATIS8 FLOAT, SATIS9 FLOAT, SATIS10 FLOAT, 
						KDV1 FLOAT, KDV2 FLOAT, KDV3 FLOAT, KDV4 FLOAT, KDV5 FLOAT, 
						KDV6 FLOAT, KDV7 FLOAT, KDV8 FLOAT, KDV9 FLOAT, KDV10 FLOAT 
					  )

INSERT INTO #KDVTABLE(FISID, SATIS1, KDV1, SATIS2, KDV2, SATIS3, KDV3, SATIS4, KDV4, SATIS5, KDV5, SATIS6, KDV6, SATIS7, KDV7, SATIS8, KDV8, SATIS9, KDV9, SATIS10, KDV10)
SELECT BELGEID, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 FROM #HRTABLE
GROUP BY BELGEID

UPDATE #KDVTABLE
SET 
	SATIS1 = CASE WHEN D.DEPARTMAN = 1 THEN D.TUTAR ELSE SATIS1 END,
	KDV1 = CASE WHEN D.DEPARTMAN = 1 THEN D.KDVTUTAR ELSE KDV1 END,
	SATIS2 = CASE WHEN D.DEPARTMAN = 2 THEN D.TUTAR ELSE SATIS2 END,
	KDV2 = CASE WHEN D.DEPARTMAN = 2 THEN D.KDVTUTAR ELSE KDV2 END,
	SATIS3 = CASE WHEN D.DEPARTMAN = 3 THEN D.TUTAR ELSE SATIS3 END,
	KDV3 = CASE WHEN D.DEPARTMAN = 3 THEN D.KDVTUTAR ELSE KDV3 END,
	SATIS4 = CASE WHEN D.DEPARTMAN = 4 THEN D.TUTAR ELSE SATIS4 END,
	KDV4 = CASE WHEN D.DEPARTMAN = 4 THEN D.KDVTUTAR ELSE KDV4 END,
	SATIS5 = CASE WHEN D.DEPARTMAN = 5 THEN D.TUTAR ELSE SATIS5 END,
	KDV5 = CASE WHEN D.DEPARTMAN = 5 THEN D.KDVTUTAR ELSE KDV5 END,
	SATIS6 = CASE WHEN D.DEPARTMAN = 6 THEN D.TUTAR ELSE SATIS6 END,
	KDV6 = CASE WHEN D.DEPARTMAN = 6 THEN D.KDVTUTAR ELSE KDV6 END,
	SATIS7 = CASE WHEN D.DEPARTMAN = 7 THEN D.TUTAR ELSE SATIS7 END,
	KDV7 = CASE WHEN D.DEPARTMAN = 7 THEN D.KDVTUTAR ELSE KDV7 END,
	SATIS8 = CASE WHEN D.DEPARTMAN = 8 THEN D.TUTAR ELSE SATIS8 END,
	KDV8 = CASE WHEN D.DEPARTMAN = 8 THEN D.KDVTUTAR ELSE KDV8 END,
	SATIS9 = CASE WHEN D.DEPARTMAN = 9 THEN D.TUTAR ELSE SATIS9 END,
	KDV9 = CASE WHEN D.DEPARTMAN = 9 THEN D.KDVTUTAR ELSE KDV9 END,
	SATIS10 = CASE WHEN D.DEPARTMAN = 10 THEN D.TUTAR ELSE SATIS10 END,
	KDV10 = CASE WHEN D.DEPARTMAN = 10 THEN D.KDVTUTAR ELSE KDV10 END
FROM #KDVTABLE K 
	INNER JOIN (
				SELECT 
					BELGEID,
					DEPARTMAN,
					SUM(TUTAR) AS TUTAR,
					SUM(KDVTUTAR) AS KDVTUTAR
				FROM #HRTABLE
				WHERE TIP = 1
				GROUP BY BELGEID, DEPARTMAN
				) AS D ON D.BELGEID = K.FISID

INSERT INTO #HRTABLE(BELGEID, ISIPTAL, SATIRNO, DATA, TIP)
SELECT
	K.FISID,
	CASE WHEN F.TIP = 3 THEN 1 ELSE 0 END,
	H.MAXSATIRNO+1,
	'06 '+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS1)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS2)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS3)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS4)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS5)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS6)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS7)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS8)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS9)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.SATIS10)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV1)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV2)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV3)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV4)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV5)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV6)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV7)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV8)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV9)),'.',','),15)+
	dbo.SR(REPLACE(CONVERT(VARCHAR, ABS(K.KDV10)),'.',','),15),
	3
FROM #KDVTABLE K WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = K.FISID
	INNER JOIN (SELECT BELGEID, MAX(SATIRNO) MAXSATIRNO FROM #HRTABLE GROUP BY BELGEID) H ON H.BELGEID = K.FISID


SELECT DATA FROM #HRTABLE
ORDER BY ISIPTAL, BELGEID, SATIRNO

DROP TABLE #KDVTABLE
DROP TABLE #HRTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_OUTPUT_MESSAGE]
	@MESSAGE NVARCHAR(4000)
AS
	SET @MESSAGE = @MESSAGE + ' --> ' + CONVERT(VARCHAR, GETDATE(),114)
	RAISERROR(@MESSAGE,10, 1) with nowait
	RAISERROR('',10, 1) with nowait
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_TO_FIS_MAIN]
	@KASANO INT
AS
SET NOCOUNT ON

SET @KASANO = ISNULL(@KASANO, 1)

BEGIN TRAN

DECLARE 
	@ZTARIH		DATETIME, 
	@BELGEKODU	VARCHAR(20),
	@BELGEID	INT,
	@TARIH		DATETIME,
	@FISID		INT,
	@FISCOUNT	INT,
	@TOPLAMTUTAR MONEY,
	@CARIKODU	VARCHAR(20),
	@CARIADI	VARCHAR(50),
	@SATIRNO	INT,
	@PLUNO		INT,
	@BARKOD		VARCHAR(20),
	@STOKADI	VARCHAR(50),
	@KDV		FLOAT,
	@DEPARTMAN	INT,
	@MIKTAR		FLOAT,
	@BIRIM		VARCHAR(10),
	@FIYAT		FLOAT,
	@TUTAR		FLOAT,
	@KREDINO	INT,
	@KREDITIPI  VARCHAR(50),
	@KREDITUTAR	FLOAT,
	@ERRORMESSAGE	VARCHAR(4000)

SELECT @ZTARIH = MAX(TARIH) FROM TBL_XZ_LOG WITH (NOLOCK) WHERE TIP = 'Z'
SET @ZTARIH = ISNULL(@ZTARIH, GETDATE()-365)

DECLARE CURR CURSOR FAST_FORWARD FOR
SELECT ID, CREATEDATE, ISNULL(CUSTOMERPHONE,''), ISNULL(CUSTOMERNAME,''), ORDERTOTAL FROM TBL_SIPARIS_PLATFORM_MAIN
WHERE ISNULL(POSFISID,0) = 0 AND PLATFORMTYPE = 1 AND ORDERSTATE = 3
ORDER BY CREATEDATE ASC
OPEN CURR

FETCH NEXT FROM CURR
INTO @BELGEID, @TARIH, @CARIKODU, @CARIADI, @TOPLAMTUTAR

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT @FISCOUNT = COUNT(*) FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE KASANO = @KASANO AND TARIH >= @ZTARIH

	SET @FISCOUNT = ISNULL(@FISCOUNT,0) + 1
	SET @BELGEKODU = dbo.ZL(CONVERT(VARCHAR, @FISCOUNT),6)
	BEGIN TRY
		INSERT INTO TBL_FIS_MAIN(KASANO, BELGEKODU, TARIH, TIP, CARIKODU, CARIADI, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PARAUSTU, VERGINO, ISEFATURA, EFATURAKODU, UUID, ALIAS, PUAN, ISSENDPUAN, ACIKLAMA, YETKILIKODU, YETKILIADI)
		SELECT @KASANO, @BELGEKODU, @TARIH, 0, @CARIKODU, @CARIADI, @TOPLAMTUTAR, 0, 0, 0, 0, '0999', 'BARPOS', 0, '', 0, '', '', '', 0, 0, '', '', '' 
	
		SELECT @FISID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0 ROLLBACK TRAN
		CLOSE CURR
		DEALLOCATE CURR
		SET @ERRORMESSAGE = CONVERT(VARCHAR, @BELGEID)+' IDLİ SİPARİŞ ÜST BİLGİSİ HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE, 16, 1)
		RETURN
	END CATCH
	
	DECLARE CURRD CURSOR FAST_FORWARD FOR
	SELECT 
		ROW_NUMBER() OVER(ORDER BY D.ID ASC),
		ISNULL(S.PLUNO,0),
		D.PRODUCTID,
		D.NAME,
		ISNULL(S.KDV,0),
		ISNULL(S.DEPARTMAN,1),
		D.QUANTITY,
		ISNULL(S.BIRIM,'ADET'),
		D.PRICE,
		D.LISTPRICE
	FROM TBL_SIPARIS_PLATFORM_DETAY D WITH (NOLOCK)
		LEFT JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.PRODUCTID
	WHERE BELGEID = @BELGEID
	OPEN CURRD

	FETCH NEXT FROM CURRD
	INTO @SATIRNO, @PLUNO, @BARKOD, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR		
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		BEGIN TRY
			INSERT INTO TBL_FIS_DETAY(FISID, SATIRNO, TIP, PLUNO, BARKOD, STOKADI, KDV, DEPARTMAN, MIKTAR, BIRIM, FIYAT, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PLASIYERKODU, PLASIYERADI, ACIKLAMA, BARKODTYPE, DOVIZKODU, DOVIZKURU, DOVIZTUTARI, PUAN)
			SELECT @FISID, @SATIRNO, 'SAT', @PLUNO, @BARKOD, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR, 0, 0, 0, 0, '0999', 'BARPOS', '', '', '', 0, 'TL', 1, @TUTAR, 0
		END TRY
		BEGIN CATCH
			IF @@TRANCOUNT > 0 ROLLBACK TRAN
			CLOSE CURRD
			DEALLOCATE CURRD
			CLOSE CURR
			DEALLOCATE CURR
			SET @ERRORMESSAGE = CONVERT(VARCHAR, @BELGEID)+' IDLİ SİPARİŞ '+@BARKOD+' BARKODLU ÜRÜNDE HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE, 16, 1)
			RETURN
		END CATCH
		
		FETCH NEXT FROM CURRD
		INTO @SATIRNO, @PLUNO, @BARKOD, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR		
	END
	CLOSE CURRD
	DEALLOCATE CURRD

	DECLARE CURRD CURSOR FAST_FORWARD FOR
	SELECT KREDINO, ACIKLAMA, TUTAR
	FROM TBL_SIPARIS_PLATFORM_PAYMENT D WITH (NOLOCK)
	WHERE BELGEID = @BELGEID
	OPEN CURRD

	FETCH NEXT FROM CURRD
	INTO @KREDINO, @KREDITIPI, @KREDITUTAR	
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		BEGIN TRY		
			INSERT INTO TBL_FIS_ODEME(FISID, KREDINO, KREDITIPI, TUTAR, DOVIZKODU, DOVIZKURU, DOVIZTUTARI)
			SELECT @FISID, @KREDINO, @KREDITIPI, @KREDITUTAR, 'TL', 1, @KREDITUTAR
		END TRY
		BEGIN CATCH
			IF @@TRANCOUNT > 0 ROLLBACK TRAN
			CLOSE CURRD
			DEALLOCATE CURRD
			CLOSE CURR
			DEALLOCATE CURR
			SET @ERRORMESSAGE = CONVERT(VARCHAR, @BELGEID)+' IDLİ SİPARİŞ '+@KREDITIPI+' TİPLİ ÖDEME TİPİNDE HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE, 16, 1)
			RETURN
		END CATCH

		FETCH NEXT FROM CURRD
		INTO @KREDINO, @KREDITIPI, @KREDITUTAR	
	END
	CLOSE CURRD
	DEALLOCATE CURRD	

	BEGIN TRY		
		UPDATE TBL_SIPARIS_PLATFORM_MAIN
		SET POSFISID = @FISID
		WHERE ID = @BELGEID
	END TRY
	BEGIN CATCH
		IF @@TRANCOUNT > 0 ROLLBACK TRAN
		CLOSE CURR
		DEALLOCATE CURR
		SET @ERRORMESSAGE = CONVERT(VARCHAR, @BELGEID)+' IDLİ SİPARİŞ POS FİŞ UPDATE SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE, 16, 1)
		RETURN
	END CATCH

	FETCH NEXT FROM CURR
	INTO @BELGEID, @TARIH, @CARIKODU, @CARIADI, @TOPLAMTUTAR
END

CLOSE CURR
DEALLOCATE CURR

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_PAYMENT_DELETE]
	@BELGEID		INT
AS

	DELETE FROM TBL_SIPARIS_PLATFORM_PAYMENT
	WHERE BELGEID = @BELGEID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_PAYMENT_INSERT]
	@BELGEID		INT,
	@ODEMETIPI		INT,
	@TAKSITSAYISI	INT,
	@KREDINO		INT,
	@BKMNO			VARCHAR(20),
	@TUTAR			FLOAT,
	@ACIKLAMA		VARCHAR(MAX),
	@KARTNO			VARCHAR(50)
AS

	INSERT INTO TBL_SIPARIS_PLATFORM_PAYMENT(BELGEID, ODEMETIPI, TAKSITSAYISI, KREDINO, BKMNO, TUTAR, ACIKLAMA, KARTNO, CREATEDATE)
	SELECT @BELGEID, @ODEMETIPI, @TAKSITSAYISI, @KREDINO, @BKMNO, @TUTAR, @ACIKLAMA, @KARTNO, GETDATE()

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_DETAY_LIST] 
	@BELGEID	INT
AS
	SELECT 
		D.ID, 
		D.BELGEID, 
		D.PRODUCTID, 
		D.NAME, 
		ISNULL(S.KDV,8) AS KDV,
		D.PRICE, 
		D.LISTPRICE, 
		D.QUANTITY, 
		D.ORDERINDEX,
		D.CREATEDATE, 
		D.CHANGEDATE
	FROM TBL_SIPARIS_PLATFORM_DETAY D WITH (NOLOCK)
		LEFT JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.PRODUCTID
	WHERE D.BELGEID = @BELGEID
	ORDER BY D.ID ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[PR_SIPARIS_PLATFORM_MAIN]
	@ID					INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)

	SELECT 
		ID, 
		PLATFORMTYPE,
		CASE PLATFORMTYPE WHEN 0 THEN 'YEMEK SEPETI' ELSE 'MAHALLEM' END AS PLATFORM,
		ORDERID, 
		MESSAGEID, 
		RESTAURANTNAME, 
		CUSTOMERNAME, 
		PAYMENTNOTE, 
		ORDERTOTAL, 
		CUSTOMERPHONE, 
		CUSTOMERPHONE2, 
		PROMOCODE, 
		CITY, 
		REGION, 
		ORGANIZATION, 
		ADDRESS, 
		ADDRESSDESCIPTION, 
		PAYMENTMETHODID, 
		CASE PLATFORMTYPE
			WHEN 0 THEN --YEMEK SEPETI
				CASE PAYMENTMETHODID 
					WHEN 1 THEN 'NAKIT'
					WHEN 2 THEN 'TICKET KUPON'
					WHEN 3 THEN 'MULTINET KARTI'
					WHEN 4 THEN	'ONLINE KREDI KARTI'
					WHEN 5 THEN 'SODEXHO KUPON'
					WHEN 6 THEN 'KREDI KARTI/POS'
					WHEN 8 THEN 'ADVANTAGE CARD'
					WHEN 9 THEN 'MAXIMA CARD'
					WHEN 10 THEN 'SMARTICKET/POS'
					WHEN 11 THEN 'PASSCARD/POS'
					WHEN 12 THEN 'BISTRA/POS'
					WHEN 13 THEN 'WINWIN'
					WHEN 14 THEN 'SET YEMEK CEKI'
					WHEN 15 THEN 'SETCARD/POS'
					WHEN 16 THEN 'CEPBANK'
					WHEN 17 THEN 'CEK'
					WHEN 18 THEN 'WINWIN/POS'
					WHEN 19 THEN 'ENPARA/ENCARD'
					WHEN 20 THEN 'TEB KREDI KARTI'
					WHEN 21 THEN 'NAKİT'
					WHEN 22 THEN 'FASTPAY'
					WHEN 23 THEN 'CÜZDAN'
					WHEN 24 THEN 'METROPOL/POS'
				ELSE 'BILINMIYOR' END 
			WHEN 1 THEN --MAHALLEM
				CASE PAYMENTMETHODID 
					WHEN 0 THEN 'NAKIT'
					WHEN 1 THEN 'KREDI'
					WHEN 2 THEN 'ONLINE'
				ELSE 'BILINMIYOR' END
		END AS PAYMENTMETHOD, 		
		DELIVERYTIME, 
		CHANGEINTOTAL, 
		ORDERNOTE, 
		ORDERSTATE,
		CASE ORDERSTATE 
			WHEN 1 THEN 'YENİ SİPARİŞ' 
			WHEN 2 THEN 'SİPARİŞ ALINDI' 
			WHEN 3 THEN 'TAHSİL EDİLDİ' 
			WHEN 5 THEN 'HAZIRLANIYOR' 
			WHEN 6 THEN 'SİPARİŞ YOLDA'
			WHEN 7 THEN 'ESNAFA İLETİLDİ'
			WHEN 8 THEN 'İPTAL EDİLDİ' 
			WHEN 9 THEN 'ESNAF TARAFINDAN İPTAL EDİLDİ' 
			WHEN 10 THEN 'ÜRÜN OLMADIĞINDAN İPTAL EDİLDİ' 
			WHEN 11 THEN 'KURYE ÇAĞIRILDI' 
		ELSE 'BİLİNMİYOR' END AS STATEDESCRIPTION,
		KURYEADI,
		POSID AS CEKNO,
		CREATEDATE, 
		CHANGEDATE
	FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
	WHERE
		ID = ISNULL(@ID, ID) 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_MAIN_LIST]
	@ID					INT = NULL,
	@ORDERSTATES		VARCHAR(MAX) = NULL,
	@PLATFORMTYPES		VARCHAR(MAX) = NULL
AS
	IF @ORDERSTATES IS NULL
		SET @ORDERSTATES = '1,2,3,4,5,6,7,8,9,10,11'
	IF @PLATFORMTYPES IS NULL
		SET @PLATFORMTYPES = '0,1'
	SELECT 
		ID, 
		PLATFORMTYPE,
		CASE PLATFORMTYPE WHEN 0 THEN 'YEMEK SEPETI' ELSE 'MAHALLEM' END AS PLATFORM,
		ORDERID, 
		MESSAGEID, 
		RESTAURANTNAME, 
		CUSTOMERNAME, 
		PAYMENTNOTE, 
		ORDERTOTAL, 
		CUSTOMERPHONE, 
		CUSTOMERPHONE2, 
		PROMOCODE, 
		CITY, 
		REGION, 
		ORGANIZATION, 
		ADDRESS, 
		ADDRESSDESCIPTION, 
		PAYMENTMETHODID, 
		CASE PLATFORMTYPE
			WHEN 0 THEN --YEMEK SEPETI
				CASE PAYMENTMETHODID 
					WHEN 1 THEN 'NAKIT'
					WHEN 2 THEN 'TICKET KUPON'
					WHEN 3 THEN 'MULTINET KARTI'
					WHEN 4 THEN	'ONLINE KREDI KARTI'
					WHEN 5 THEN 'SODEXHO KUPON'
					WHEN 6 THEN 'KREDI KARTI/POS'
					WHEN 8 THEN 'ADVANTAGE CARD'
					WHEN 9 THEN 'MAXIMA CARD'
					WHEN 10 THEN 'SMARTICKET/POS'
					WHEN 11 THEN 'PASSCARD/POS'
					WHEN 12 THEN 'BISTRA/POS'
					WHEN 13 THEN 'WINWIN'
					WHEN 14 THEN 'SET YEMEK CEKI'
					WHEN 15 THEN 'SETCARD/POS'
					WHEN 16 THEN 'CEPBANK'
					WHEN 17 THEN 'CEK'
					WHEN 18 THEN 'WINWIN/POS'
					WHEN 19 THEN 'ENPARA/ENCARD'
					WHEN 20 THEN 'TEB KREDI KARTI'
					WHEN 21 THEN 'NAKİT'
					WHEN 22 THEN 'FASTPAY'
					WHEN 23 THEN 'CÜZDAN'
					WHEN 24 THEN 'METROPOL/POS'
				ELSE 'BILINMIYOR' END 
			WHEN 1 THEN --MAHALLEM
				CASE PAYMENTMETHODID 
					WHEN 0 THEN 'NAKIT'
					WHEN 1 THEN 'KREDI'
					WHEN 2 THEN 'ONLINE'
				ELSE 'BILINMIYOR' END
		END AS PAYMENTMETHOD, 		
		DELIVERYTIME, 
		CHANGEINTOTAL, 
		ORDERNOTE, 
		ORDERSTATE,
		CASE ORDERSTATE 
			WHEN 1 THEN 'YENİ SİPARİŞ' 
			WHEN 2 THEN 'SİPARİŞ ALINDI' 
			WHEN 3 THEN 'TAHSİL EDİLDİ' 
			WHEN 5 THEN 'HAZIRLANIYOR' 
			WHEN 6 THEN 'SİPARİŞ YOLDA'
			WHEN 7 THEN 'ESNAFA İLETİLDİ'
			WHEN 8 THEN 'İPTAL EDİLDİ' 
			WHEN 9 THEN 'ESNAF TARAFINDAN İPTAL EDİLDİ' 
			WHEN 10 THEN 'ÜRÜN OLMADIĞINDAN İPTAL EDİLDİ' 
			WHEN 11 THEN 'KURYE ÇAĞIRILDI' 
		ELSE 'BİLİNMİYOR' END AS STATEDESCRIPTION,
		KURYEADI,
		POSID,
		TERMINALNO,
		CREATEDATE, 
		CHANGEDATE
	FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
	WHERE
		ID = ISNULL(@ID, ID) AND
		PLATFORMTYPE IN (SELECT CODE FROM dbo.GETPARAMS(@PLATFORMTYPES)) AND
		ORDERSTATE IN (SELECT CODE FROM dbo.GETPARAMS(@ORDERSTATES))
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_MAIN_INSERT_UPDATE]
	@PLATFORMTYPE		TINYINT,
	@ORDERID			VARCHAR(50),
	@MESSAGEID			INT			= NULL,
	@RESTAURANTNAME		VARCHAR(255) = NULL,
	@CUSTOMERNAME		VARCHAR(255) = NULL,
	@PAYMENTNOTE		VARCHAR(MAX)= NULL ,
	@ORDERTOTAL			MONEY = NULL,
	@CUSTOMERPHONE		VARCHAR(50) =  NULL,
	@CUSTOMERPHONE2		VARCHAR(50)	= NULL ,
	@PROMOCODE			VARCHAR(50)	= NULL ,
	@CITY				VARCHAR(50)	= NULL ,
	@REGION				VARCHAR(50)	= NULL ,
	@ORGANIZATION		VARCHAR(255)= NULL ,
	@ADDRESS			VARCHAR(MAX)= NULL ,
	@ADDRESSDESCIPTION	VARCHAR(MAX)= NULL ,
	@PAYMENTMETHODID	INT = NULL,
	@DELIVERYTIME		DATETIME = NULL,
	@CHANGEINTOTAL		MONEY		= NULL ,
	@ORDERNOTE			VARCHAR(MAX)= NULL ,
	@ORDERSTATE			TINYINT = NULL,
	@KURYEADI			VARCHAR(50) = NULL,
	@POSFISID			INT = NULL	
AS
	DECLARE @ID	INT	
	
	SELECT @ID = ID FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
	WHERE PLATFORMTYPE = @PLATFORMTYPE AND ORDERID = @ORDERID

	IF @ID IS NULL
		INSERT INTO TBL_SIPARIS_PLATFORM_MAIN(PLATFORMTYPE, ORDERID, MESSAGEID, RESTAURANTNAME, CUSTOMERNAME, PAYMENTNOTE, ORDERTOTAL, CUSTOMERPHONE, CUSTOMERPHONE2, PROMOCODE, CITY, REGION, ORGANIZATION, ADDRESS, ADDRESSDESCIPTION, PAYMENTMETHODID, DELIVERYTIME, CHANGEINTOTAL, ORDERNOTE, ORDERSTATE, CREATEDATE)
		SELECT @PLATFORMTYPE, @ORDERID, @MESSAGEID, @RESTAURANTNAME, @CUSTOMERNAME, @PAYMENTNOTE, @ORDERTOTAL, @CUSTOMERPHONE, @CUSTOMERPHONE2, @PROMOCODE, @CITY, @REGION, @ORGANIZATION, @ADDRESS, @ADDRESSDESCIPTION, @PAYMENTMETHODID, @DELIVERYTIME, @CHANGEINTOTAL, @ORDERNOTE, @ORDERSTATE, GETDATE()
	ELSE
		UPDATE TBL_SIPARIS_PLATFORM_MAIN
		SET 
			MESSAGEID			= @MESSAGEID, 
			RESTAURANTNAME		= ISNULL(@RESTAURANTNAME	, RESTAURANTNAME	), 
			CUSTOMERNAME		= ISNULL(@CUSTOMERNAME		, CUSTOMERNAME		), 
			PAYMENTNOTE			= ISNULL(@PAYMENTNOTE		, PAYMENTNOTE		), 
			ORDERTOTAL			= ISNULL(@ORDERTOTAL		, ORDERTOTAL		), 
			CUSTOMERPHONE		= ISNULL(@CUSTOMERPHONE		, CUSTOMERPHONE		), 
			CUSTOMERPHONE2		= ISNULL(@CUSTOMERPHONE2	, CUSTOMERPHONE2	), 
			PROMOCODE			= ISNULL(@PROMOCODE			, PROMOCODE			), 
			CITY				= ISNULL(@CITY				, CITY				), 
			REGION				= ISNULL(@REGION			, REGION			), 
			ORGANIZATION		= ISNULL(@ORGANIZATION		, ORGANIZATION		), 
			ADDRESS				= ISNULL(@ADDRESS			, ADDRESS			), 
			ADDRESSDESCIPTION	= ISNULL(@ADDRESSDESCIPTION	, ADDRESSDESCIPTION	), 
			PAYMENTMETHODID		= ISNULL(@PAYMENTMETHODID	, PAYMENTMETHODID	), 
			DELIVERYTIME		= ISNULL(@DELIVERYTIME		, DELIVERYTIME		), 
			CHANGEINTOTAL		= ISNULL(@CHANGEINTOTAL		, CHANGEINTOTAL		), 
			ORDERNOTE			= ISNULL(@ORDERNOTE			, ORDERNOTE			), 
			ORDERSTATE			= ISNULL(@ORDERSTATE		, ORDERSTATE		), 
			KURYEADI			= ISNULL(@KURYEADI			, KURYEADI			),
			POSFISID			= ISNULL(@POSFISID			, POSFISID			),
			CHANGEDATE			= GETDATE()
		WHERE ID = @ID

	RETURN ISNULL((
				SELECT ID FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
				WHERE PLATFORMTYPE = @PLATFORMTYPE AND ORDERID = @ORDERID
			),-1)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_DETAY_INSERT_UPDATE]
	@BELGEID	INT, 
	@PRODUCTID	VARCHAR(50), 
	@NAME		VARCHAR(255), 
	@PRICE		MONEY, 
	@LISTPRICE	MONEY, 
	@QUANTITY	MONEY,
	@ORDERINDEX	INT
AS
	SET NOCOUNT ON

	DECLARE	@ID	INT 

	SELECT @ID = ID FROM TBL_SIPARIS_PLATFORM_DETAY WITH (NOLOCK)
	WHERE BELGEID = @BELGEID AND PRODUCTID = @PRODUCTID AND ORDERINDEX = @ORDERINDEX
	

	IF @ID IS NULL
	BEGIN
		INSERT INTO TBL_SIPARIS_PLATFORM_DETAY(BELGEID, PRODUCTID, NAME, PRICE, LISTPRICE, QUANTITY, ORDERINDEX, CREATEDATE)
		SELECT @BELGEID, @PRODUCTID, @NAME, @PRICE, @LISTPRICE, @QUANTITY, @ORDERINDEX, GETDATE()
	
		SELECT @ID = MAX(ID) FROM TBL_SIPARIS_PLATFORM_DETAY WITH (NOLOCK) WHERE BELGEID = @BELGEID AND PRODUCTID = @PRODUCTID 
	END
	ELSE
	BEGIN
		UPDATE TBL_SIPARIS_PLATFORM_DETAY
		SET 
			BELGEID		= ISNULL(@BELGEID, BELGEID), 
			PRODUCTID	= ISNULL(@PRODUCTID,PRODUCTID), 
			NAME		= ISNULL(@NAME, NAME), 
			PRICE		= ISNULL(@PRICE, PRICE), 
			LISTPRICE	= ISNULL(@LISTPRICE, LISTPRICE),
			QUANTITY	= ISNULL(@QUANTITY, QUANTITY),
			CHANGEDATE	= GETDATE()
		WHERE ID = @ID
	END

	RETURN @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_OPTION_INSERT_UPDATE]
	@DETAYID	INT, 
	@OPTIONID	VARCHAR(50), 
	@NAME		VARCHAR(255)
AS
DECLARE @ID	INT

	SELECT @ID = ID FROM TBL_SIPARIS_PLATFORM_OPTION WITH (NOLOCK)
	WHERE DETAYID = @DETAYID AND OPTIONID = @OPTIONID
 

	SET NOCOUNT ON

	IF @ID IS NULL
	BEGIN
		INSERT INTO TBL_SIPARIS_PLATFORM_OPTION(DETAYID, OPTIONID, NAME)
		SELECT @DETAYID, @OPTIONID, @NAME
	
		SELECT @ID = MAX(ID) FROM TBL_SIPARIS_PLATFORM_OPTION WITH (NOLOCK) WHERE DETAYID = @ID AND OPTIONID = @OPTIONID	
	END
	ELSE
		UPDATE TBL_SIPARIS_PLATFORM_OPTION
		SET 
			DETAYID		= ISNULL(@DETAYID, DETAYID), 
			OPTIONID	= ISNULL(@OPTIONID,OPTIONID), 
			NAME		= ISNULL(@NAME, NAME)
		WHERE ID = @ID

	RETURN @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_OPTION_LIST]
	@DETAYID	INT
AS
	SELECT ID, DETAYID, OPTIONID, NAME FROM TBL_SIPARIS_PLATFORM_OPTION WITH (NOLOCK)
	WHERE DETAYID = @DETAYID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_DETAY_OPTION_LIST] 
	@BELGEID	INT = 22
AS

SELECT DETAYID, NAME = STUFF((
    SELECT N', ' + NAME FROM TBL_SIPARIS_PLATFORM_OPTION
    WHERE DETAYID = x.DETAYID
    FOR XML PATH(''), TYPE).value(N'.[1]', N'nvarchar(max)'), 1, 2, N'')
INTO #OPTIONTBL FROM TBL_SIPARIS_PLATFORM_OPTION AS x
WHERE DETAYID IN (SELECT ID FROM TBL_SIPARIS_PLATFORM_DETAY WITH (NOLOCK) WHERE BELGEID = @BELGEID)
GROUP BY DETAYID
ORDER BY DETAYID

	SELECT 
		D.PRODUCTID,
		D.NAME + CASE WHEN O.NAME IS NULL THEN '' ELSE '( '+O.NAME + ' )' END AS NAME, 
		D.QUANTITY, 
		D.LISTPRICE,
		CONVERT(BIT,0) AS ISEXISTS
	FROM TBL_SIPARIS_PLATFORM_DETAY D WITH (NOLOCK)
		LEFT JOIN #OPTIONTBL O ON O.DETAYID = D.ID
	WHERE D.BELGEID = @BELGEID
	ORDER BY ID ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_SIPARIS_PLATFORM_DETAY]
	@ID					INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
	SELECT 
		ID, 
		BELGEID, 
		PRODUCTID, 
		NAME, 
		PRICE, 
		LISTPRICE, 
		QUANTITY, 
		ORDERINDEX,
		CREATEDATE, 
		CHANGEDATE
	FROM TBL_SIPARIS_PLATFORM_DETAY WITH (NOLOCK)
	WHERE BELGEID = @ID
	ORDER BY ID ASC
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_SIPARIS_PLATFORM_OPTION]
	@ID					INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)

	SELECT ID, DETAYID, OPTIONID, NAME FROM TBL_SIPARIS_PLATFORM_OPTION WITH (NOLOCK)
	WHERE DETAYID IN(SELECT ID FROM TBL_SIPARIS_PLATFORM_DETAY WITH (NOLOCK) WHERE BELGEID = @ID)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_GET_DETAY_LIST]
	@SIPARISID INT
AS

	DECLARE @PLATFORMTYPE INT
	SELECT @PLATFORMTYPE = PLATFORMTYPE FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
	WHERE ID = @SIPARISID

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, TIP VARCHAR(1), DETAYID INT, BARKOD VARCHAR(20), ACIKLAMA VARCHAR(50), MIKTAR MONEY, TUTAR MONEY)

	INSERT INTO #RETTABLE(TIP, DETAYID, BARKOD, ACIKLAMA, MIKTAR, TUTAR)
	SELECT 'U', D.ID, D.PRODUCTID AS BARKOD, '', D.QUANTITY, D.LISTPRICE 
	FROM TBL_SIPARIS_PLATFORM_DETAY D
	WHERE D.BELGEID = @SIPARISID

	UPDATE #RETTABLE
	SET ACIKLAMA = STOKADI
	FROM #RETTABLE R 
		INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = R.BARKOD
	
	SELECT * FROM #RETTABLE
	ORDER BY DETAYID ASC, ID ASC

	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_SATIS_REPORT]
	@ILKTARIH	SMALLDATETIME = NULL,
	@SONTARIH	SMALLDATETIME = NULL
AS
	IF @ILKTARIH IS NULL
	BEGIN
		SET @ILKTARIH = '11/30/2018'
		SET @SONTARIH = '12/01/2018'
	END

	SELECT 
		ID, 
		DELIVERYTIME, 
		PLATFORMTYPE,
		CASE PLATFORMTYPE WHEN 0 THEN 'YEMEK SEPETI' ELSE 'MAHALLEM' END AS PLATFORM,
		ORDERID, 
		CUSTOMERNAME, 
		ORDERTOTAL, 
		CASE ORDERSTATE 
			WHEN 1 THEN 'YENİ SİPARİŞ' 
			WHEN 2 THEN 'SİPARİŞ ALINDI' 
			WHEN 3 THEN 'TAHSİL EDİLDİ' 
			WHEN 5 THEN 'HAZIRLANIYOR' 
			WHEN 6 THEN 'SİPARİŞ YOLDA'
			WHEN 7 THEN 'ESNAFA İLETİLDİ'
			WHEN 8 THEN 'İPTAL EDİLDİ' 
			WHEN 9 THEN 'ESNAF TARAFINDAN İPTAL EDİLDİ' 
			WHEN 10 THEN 'ÜRÜN OLMADIĞINDAN İPTAL EDİLDİ' 
			WHEN 11 THEN 'KURYE ÇAĞIRILDI' 
		ELSE 'BİLİNMİYOR' END AS STATEDESCRIPTION,
		KURYEADI,
		CUSTOMERPHONE, 
		ADDRESS, 
		REGION, 
		CITY, 
		CASE PLATFORMTYPE
			WHEN 0 THEN --YEMEK SEPETI
				CASE PAYMENTMETHODID 
					WHEN 1 THEN 'NAKIT'
					WHEN 2 THEN 'TICKET KUPON'
					WHEN 3 THEN 'MULTINET KARTI'
					WHEN 4 THEN	'ONLINE KREDI KARTI'
					WHEN 5 THEN 'SODEXHO KUPON'
					WHEN 6 THEN 'KREDI KARTI/POS'
					WHEN 8 THEN 'ADVANTAGE CARD'
					WHEN 9 THEN 'MAXIMA CARD'
					WHEN 10 THEN 'SMARTICKET/POS'
					WHEN 11 THEN 'PASSCARD/POS'
					WHEN 12 THEN 'BISTRA/POS'
					WHEN 13 THEN 'WINWIN'
					WHEN 14 THEN 'SET YEMEK CEKI'
					WHEN 15 THEN 'SETCARD/POS'
					WHEN 16 THEN 'CEPBANK'
					WHEN 17 THEN 'CEK'
					WHEN 18 THEN 'WINWIN/POS'
					WHEN 19 THEN 'ENPARA/ENCARD'
					WHEN 20 THEN 'TEB KREDI KARTI'
					WHEN 21 THEN 'NAKİT'
					WHEN 22 THEN 'FASTPAY'
					WHEN 23 THEN 'CÜZDAN'
					WHEN 24 THEN 'METROPOL/POS'
				ELSE 'BILINMIYOR' END 
			WHEN 1 THEN --MAHALLEM
				CASE PAYMENTMETHODID 
					WHEN 0 THEN 'NAKIT'
					WHEN 1 THEN 'KREDI'
					WHEN 2 THEN 'ONLINE'
				ELSE 'BILINMIYOR' END
		END AS PAYMENTMETHOD, 		
		ORDERNOTE
	FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
	WHERE 
		DELIVERYTIME >= @ILKTARIH AND
		DELIVERYTIME <= (@SONTARIH+1)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_SIPARIS_PLATFORM_SIPARIS_STOK_KONTROL] 
	@SIPARISID INT
AS

	DECLARE @PLATFORMTYPE INT
	SELECT @PLATFORMTYPE = PLATFORMTYPE FROM TBL_SIPARIS_PLATFORM_MAIN WITH (NOLOCK)
	WHERE ID = @SIPARISID

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, TIP VARCHAR(1), DETAYID INT)

	INSERT INTO #RETTABLE(TIP, DETAYID)
	SELECT 'U', D.ID 
	FROM TBL_SIPARIS_PLATFORM_DETAY D
		LEFT JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.PRODUCTID
	WHERE D.BELGEID = @SIPARISID AND S.ID IS NULL

	SELECT  
		ISNULL((SELECT COUNT(*) FROM #RETTABLE WHERE TIP = 'U'),0) AS URUNCOUNT,
		ISNULL((SELECT COUNT(*) FROM #RETTABLE WHERE TIP = 'O'),0) AS OZELLIKCOUNT

	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_MAIN_INSERT]
	@KASANO			INT,
	@BELGEKODU		VARCHAR(20),
	@TARIH			DATETIME,
	@TIP			TINYINT,
	@VERGINO		VARCHAR(20),
	@CARIKODU		VARCHAR(20),
	@CARIADI		VARCHAR(50),
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PARAUSTU		FLOAT,
	@ISEFATURA		BIT,
	@EFATURAKODU	VARCHAR(20),
	@UUID			VARCHAR(50),
	@ALIAS			VARCHAR(MAX),
	@PUAN			FLOAT,
	@ISSENDPUAN		BIT,
	@ACIKLAMA		VARCHAR(MAX) = NULL,
	@YETKILIKODU	VARCHAR(4) = NULL,
	@YETKILIADI		VARCHAR(20) = NULL
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_MAIN(KASANO, BELGEKODU, TARIH, TIP, VERGINO, CARIKODU, CARIADI, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PARAUSTU, ISEFATURA, EFATURAKODU, UUID, ALIAS, PUAN, ISSENDPUAN, ACIKLAMA, YETKILIKODU, YETKILIADI)
	SELECT @KASANO, @BELGEKODU, @TARIH, @TIP, @VERGINO, @CARIKODU, @CARIADI, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PARAUSTU, @ISEFATURA, @EFATURAKODU, @UUID, @ALIAS, @PUAN, @ISSENDPUAN, @ACIKLAMA, @YETKILIKODU, @YETKILIADI

	RETURN @@IDENTITY
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_FIS_SLIP_INSERT]
	@FISID			INT,
	@DATA			VARCHAR(MAX)
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_SLIP(FISID, DATA)
	SELECT @FISID, @DATA
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_FIS_SLIP]
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)


	SELECT * FROM TBL_FIS_SLIP WITH (NOLOCK)
	WHERE FISID = @ID
	ORDER BY ID ASC

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_FIS_KDV]
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

DECLARE
	@ARATOPIND FLOAT,
	@FISTUTAR FLOAT

	SELECT @FISTUTAR = TUTAR + ABS(INDTUTAR) - ARTTUTAR, @ARATOPIND = ABS(INDTUTAR) FROM TBL_FIS_MAIN WHERE ID = @ID

	SELECT KDV, SUM((TUTAR - ABS(INDTUTAR) + ARTTUTAR)) AS TUTAR
	INTO #KDVTBL FROM TBL_FIS_DETAY WITH (NOLOCK)
	WHERE FISID = @ID AND (TIP IN ('SAT', 'IPT'))
	GROUP BY KDV

	DELETE FROM #KDVTBL WHERE TUTAR = 0

	SELECT KDV, TUTAR - CASE WHEN @FISTUTAR = 0 THEN 0 ELSE ((TUTAR / @FISTUTAR) * @ARATOPIND) END  AS NETTUTAR INTO #RETTABLE
	FROM #KDVTBL

	SELECT
		KDV,
		ROUND(SUM((NETTUTAR / (1 + (KDV / 100.00)))),2) AS KDVMATRAHI,
		ROUND(SUM((NETTUTAR - (NETTUTAR / (1 + (KDV / 100.00))))),2) AS KDVTUTARI,
		ROUND(SUM(NETTUTAR),2) AS TUTAR
	INTO #KDVTOP FROM #RETTABLE WITH (NOLOCK)
	GROUP BY KDV
	
	SELECT *, (SELECT SUM(KDVTUTARI) FROM #KDVTOP) AS GENELKDVTUTARI FROM #KDVTOP

	DROP TABLE #KDVTBL
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_TEK_FATURA_LIST]
	@TARIH SMALLDATETIME = '04/23/2018'
AS

	SELECT 
		ID, 
		TUTAR + ABS(INDTUTAR) - ARTTUTAR AS FISTUTAR , 
		ABS(INDTUTAR) AS ARATOPIND
 	INTO #FISTBL FROM TBL_FIS_MAIN (NOLOCK) 
	WHERE 
		CONVERT(SMALLDATETIME, CONVERT(VARCHAR, TARIH, 112)) = @TARIH AND
		TIP IN (0,1)

	SELECT FISID, KDV, SUM((TUTAR + INDTUTAR + ARTTUTAR)) AS TUTAR
	INTO #KDVTBL FROM TBL_FIS_DETAY WITH (NOLOCK)
	WHERE 
		FISID IN (SELECT ID FROM #FISTBL) AND
		(TIP IN ('SAT', 'IPT'))
	GROUP BY FISID, KDV

	DELETE FROM #KDVTBL WHERE TUTAR = 0

	SELECT 
		KDV, 
		K.TUTAR - CASE WHEN F.FISTUTAR = 0 THEN 0 ELSE ((TUTAR / F.FISTUTAR) * F.ARATOPIND) END  AS NETTUTAR ,
		F.ARATOPIND
	INTO #RETTABLE FROM #KDVTBL K
		INNER JOIN #FISTBL F ON F.ID = K.FISID

	SELECT 
		K.STOKKODU, 
		SUM(D.MIKTAR) AS MIKTAR, 
		SUM(D.TUTAR - CASE WHEN F.FISTUTAR = 0 THEN 0 ELSE ((D.TUTAR / F.FISTUTAR) * F.ARATOPIND) END) AS TUTAR, 
		SUM(D.TUTAR - CASE WHEN F.FISTUTAR = 0 THEN 0 ELSE ((D.TUTAR / F.FISTUTAR) * F.ARATOPIND) END) / SUM(D.MIKTAR) AS BIRIMFIYAT, 
		MAX(D.KDV) AS KDV,
		SUM(D.TUTAR - CASE WHEN F.FISTUTAR = 0 THEN 0 ELSE ((D.TUTAR / F.FISTUTAR) * F.ARATOPIND) END) * MAX(D.KDV) / 100.00 AS KDVTUTAR  
	INTO #DETAYTBL FROM TBL_FIS_DETAY AS D WITH (NOLOCK)
		INNER JOIN TBL_STOK_KOD K WITH (NOLOCK) ON K.BARKOD = D.BARKOD
		INNER JOIN #FISTBL F ON F.ID = D.FISID
	GROUP BY K.STOKKODU
	
	SELECT 
		D.STOKKODU, 
		CONVERT(VARCHAR(MAX), 'BİLİMİYOR') AS STOKADI,
		CONVERT(VARCHAR(MAX), 'ADET') AS BIRIM,
		D.MIKTAR,
		ROUND(D.BIRIMFIYAT,4) AS FIYAT,
		D.KDV,
		ROUND(D.KDVTUTAR,2) AS KDVTUTAR,
		ROUND(D.TUTAR,2) AS TUTAR 
	INTO #DTABLE FROM #DETAYTBL D
	
	UPDATE #DTABLE 
	SET STOKADI = S.STOKADI,
		BIRIM = S.BIRIM
	FROM #DTABLE D
		INNER JOIN TBL_STOK_KOD AS K WITH (NOLOCK) ON K.STOKKODU = D.STOKKODU
		INNER JOIN TBL_STOK_MAIN AS S WITH (NOLOCK) ON S.BARKOD = K.BARKOD

	SELECT
		ROUND(SUM(NETTUTAR - ((NETTUTAR * KDV) / 100.00)),2) AS KDVMATRAHI,
		ROUND(SUM((NETTUTAR * KDV) / 100.00),2) AS KDVTUTARI,
		ROUND(SUM(NETTUTAR),2) AS TUTAR
	FROM #RETTABLE WITH (NOLOCK)
	
	SELECT * FROM #DTABLE
	
	
	DROP TABLE #DTABLE
	DROP TABLE #KDVTBL
	DROP TABLE #RETTABLE
	DROP TABLE #FISTBL
	DROP TABLE #DETAYTBL

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

		
CREATE PROCEDURE [dbo].[SP_XZ_KONTROL]
AS
DECLARE @MAXTARIH DATETIME 

SELECT @MAXTARIH = MAX(TARIH) 
FROM TBL_XZ_LOG 
WHERE TIP = 'Z'

SET @MAXTARIH = ISNULL(@MAXTARIH, GETDATE())

SELECT CASE WHEN DATEDIFF(SECOND, @MAXTARIH, GETDATE()) >= 86400 THEN 1 ELSE 0 END AS DURUM
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_FIS_ODEME_LIST]
	@FISID	INT
AS
	SELECT *
	FROM TBL_FIS_ODEME WITH (NOLOCK)
	WHERE
		FISID = @FISID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[SP_XZ_LOG_DELETE]
	@ILKTARIH	DATETIME,
	@SONTARIH	DATETIME
AS
	DELETE FROM TBL_XZ_LOG
	WHERE 
		TARIH >= dateadd(day, datediff(day, 0, @ILKTARIH), 0) AND
		TARIH < dateadd(day, datediff(day, 0, @SONTARIH)+1, 0) 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_REYON_FILE]
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRY
	SELECT
		CONVERT(INT, SUBSTRING(DATA,1,6)) AS PLUNO,
		RTRIM(SUBSTRING(DATA,8,20)) AS REYONADI
	INTO #TEMPFILE FROM TBL_IMPORT_FILE
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : REYON DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

BEGIN TRAN
	BEGIN TRY
		UPDATE TBL_STOK_MAIN
		SET REYONADI = T.REYONADI
		FROM TBL_STOK_MAIN S 
			INNER JOIN #TEMPFILE T ON T.PLUNO = S.PLUNO
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA REYON UPDATE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

DROP TABLE #TEMPFILE

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_POS_SATIS_DELETE]
	@KASANO	INT,
	@ID	INT = NULL
AS
BEGIN
	SET NOCOUNT ON;

	DELETE
	FROM TBL_POS_SATIS
	WHERE
		KASANO = @KASANO AND
		ID <= ISNULL(@ID, ID)
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_POS_SATIS_INSERT]
	@KASANO		INT,
	@TIP		VARCHAR(1),
	@PLUNO		INT = NULL,
	@MIKTAR		FLOAT = NULL,
	@FIYAT		FLOAT = NULL,
	@ODEMETIPI	TINYINT = NULL,
	@KREDINO	TINYINT = NULL,
	@TUTAR		FLOAT = NULL,
	@URUNADI	VARCHAR(50) = NULL,
	@FATURATIPI TINYINT = NULL,
	@VKN		VARCHAR(20) = NULL,
	@BELGEKODU	VARCHAR(20) = NULL,
	@BELGETARIHI SMALLDATETIME = NULL,
	@BKMNO		VARCHAR(50) = NULL
AS
BEGIN
	SET NOCOUNT ON;

	INSERT INTO TBL_POS_SATIS(KASANO, TIP, PLUNO, MIKTAR, FIYAT, ODEMETIPI, KREDINO, TUTAR, URUNADI, FATURATIPI, VKN, BELGEKODU, BELGETARIHI, ISERROR, ISSEND, ERROR, BKMNO)
	SELECT @KASANO, @TIP, @PLUNO, @MIKTAR, @FIYAT, @ODEMETIPI, @KREDINO, @TUTAR, @URUNADI, @FATURATIPI,  @VKN, @BELGEKODU, @BELGETARIHI, 0, 0, '', @BKMNO
END
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_POS_SATIS_LIST]
	@KASANO		INT,
	@ISERROR	BIT = NULL,
	@ISSEND		BIT = NULL
AS
	SET NOCOUNT ON;

	SELECT
		S.ID,
		S.KASANO,
		S.TIP,
		S.PLUNO,
		S.MIKTAR,
		S.FIYAT,
		S.ODEMETIPI,
		S.KREDINO,
		S.BKMNO,
		S.TUTAR,
		S.ISERROR,
		S.ISSEND,
		S.ERROR,
		S.URUNADI,
		S.FATURATIPI,
		S.VKN,
		S.BELGEKODU,
		S.BELGETARIHI
	FROM TBL_POS_SATIS S WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		ISERROR = ISNULL(@ISERROR,ISERROR) AND
		ISSEND = ISNULL(@ISSEND,ISSEND)
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_POS_SATIS_UPDATE]
	@ID INT,
	@ERROR VARCHAR(MAX),
	@ISSEND	BIT = NULL,
	@BELGEKODU VARCHAR(20) = NULL
AS
	UPDATE TBL_POS_SATIS
	SET ERROR = @ERROR,
		ISSEND = ISNULL(@ISSEND,ISSEND),
		ISERROR = CASE WHEN @ERROR <> '' THEN 1 ELSE 0 END,
		BELGEKODU = ISNULL(@BELGEKODU, BELGEKODU)
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_POS_STATUS]
AS
	IF EXISTS(
				SELECT TOP 1 1 FROM TBL_POS_STATUS WITH (NOLOCK)
				WHERE CREATEDATE >= DATEADD(SECOND, -3, GETDATE())
			)
		SELECT * FROM TBL_POS_STATUS WITH (NOLOCK)
	ELSE
		SELECT 'ERR' AS DURUMKODU, 'CİHAZ DURUM ALNAMADI' AS DURUMACIKLAMA, GETDATE() AS CREATEDATE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_POS_STATUS_INSERT_UPDATE]
	@DURUMKODU	VARCHAR(3),
	@DURUMACIKLAMA VARCHAR(MAX)
AS
	IF EXISTS(SELECT TOP 1 1 FROM TBL_POS_STATUS WITH (NOLOCK))
		UPDATE TBL_POS_STATUS
		SET DURUMKODU = @DURUMKODU, 
			DURUMACIKLAMA = @DURUMACIKLAMA,
			CREATEDATE = GETDATE()
	ELSE
		INSERT INTO TBL_POS_STATUS(DURUMKODU, DURUMACIKLAMA, CREATEDATE)
		SELECT @DURUMKODU, @DURUMACIKLAMA, GETDATE()
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_CARI_EFATURA_LIST]
	@IDENTIFIER	VARCHAR(MAX), 
	@AKTIF		BIT 
AS
	DECLARE @EMAIL VARCHAR(50)
	SELECT TOP 1 @EMAIL = EMAIL FROM TBL_CARI_MAIN WITH (NOLOCK) WHERE VERGINO = @IDENTIFIER
	
		SELECT 
			ID, 
			ALIAS, 
			CREATEDATE, 
			IDENTIFIER, 
			AKTIF, 
			TITLE, 
			TYPE, 
			UPDATEDATE,
			ISNULL(@EMAIL,'') AS EMAIL
		FROM TBL_CARI_EFATURA WITH (NOLOCK)
		WHERE 
			IDENTIFIER = @IDENTIFIER AND
			AKTIF = @AKTIF
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_DEPARTMAN_DELETE]
	@ID	INT
AS

		DELETE FROM TBL_DEPARTMAN
		WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_DEPARTMAN_LIST]
AS
		SELECT * FROM TBL_DEPARTMAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_DETAY_LOG_INSERT]
	@FISID					INT,
	@PLUNO					INT,
	@BARKODILKOKUTMASAATI	DATETIME,
	@DBSORGUSAATI			DATETIME,
	@DBSONUCSAATI			DATETIME,
	@EKRANAYAZIMSAATI		DATETIME
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_DETAY_LOG(FISID, PLUNO, BARKODILKOKUTMASAATI, DBSORGUSAATI, DBSONUCSAATI, EKRANAYAZIMSAATI)
	SELECT @FISID, @PLUNO, @BARKODILKOKUTMASAATI, @DBSORGUSAATI, @DBSONUCSAATI, @EKRANAYAZIMSAATI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_XZ_LOG_INSERT]
	@TIP	VARCHAR(1),
	@FISNO	VARCHAR(6),
	@TARIH	DATETIME,
	@TOPLAM	FLOAT,
	@TOPKDV	FLOAT,
	@KDVHRC	FLOAT,
	@ADET	FLOAT,
	@KASIYERADI	VARCHAR(50)
AS
	IF @TIP = 'Z'
	BEGIN
		DECLARE @ID INT
		SELECT @ID = MAX(ID)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'X' AND TARIH IN (
										SELECT MAX(TARIH)
										FROM TBL_XZ_LOG WITH (NOLOCK)
										WHERE TIP = 'X'
										)
		IF @ID IS NOT NULL
			UPDATE TBL_XZ_LOG
			SET TARIH = @TARIH
			WHERE ID = @ID
		ELSE
			INSERT INTO TBL_XZ_LOG(TIP, FISNO, TARIH, TOPLAM, TOPKDV, KDVHRC, ADET, KASIYERADI)
			SELECT 'X', @FISNO, @TARIH, @TOPLAM, @TOPKDV, @KDVHRC, @ADET, @KASIYERADI

	END

	INSERT INTO TBL_XZ_LOG(TIP, FISNO, TARIH, TOPLAM, TOPKDV, KDVHRC, ADET, KASIYERADI)
	SELECT @TIP, @FISNO, @TARIH, @TOPLAM, @TOPKDV, @KDVHRC, @ADET, @KASIYERADI
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_COUNT]
	@KASANO INT
AS
DECLARE @ZTARIH DATETIME

SELECT @ZTARIH = MAX(TARIH)
FROM TBL_XZ_LOG WITH (NOLOCK)
WHERE TIP = 'Z'

SET @ZTARIH = ISNULL(@ZTARIH, GETDATE()-365)

SELECT COUNT(*) AS FISCOUNT
FROM TBL_FIS_MAIN
WHERE
	KASANO = @KASANO AND
	TARIH >= @ZTARIH
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_FIS_LOG]
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)


	SELECT * FROM TBL_FIS_LOG WITH (NOLOCK)
	WHERE FISID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_LOG_INSERT]
	@FISID			INT,
	@ACIKLAMA		VARCHAR(MAX),
	@TIP			VARCHAR(3)
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_LOG(FISID, ACIKLAMA, TIP)
	SELECT @FISID, @ACIKLAMA, @TIP
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_FIS_PROMOSYON]
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)


	SELECT * FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
	WHERE FISID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_STOK_SATIS_ADET_REPORT]
	@KASANO		INT = NULL,
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL
AS

	IF @KASANO IS NULL
	BEGIN
		SET @KASANO = 1
		SET @ILKTARIH = '07/25/2016 00:00:01'
		SET @SONTARIH = '07/25/2016 23:59:59'
	END

SELECT
	D.BARKOD,
	D.STOKADI,
	SUM(
			CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END  *
			CASE WHEN D.TIP = 'IPT' THEN -1 ELSE 1 END *
			ABS(D.MIKTAR)
		) AS MIKTAR,
	SUM(
		CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END  *
		CASE WHEN D.TIP = 'IPT' THEN -1 ELSE 1 END *
		ABS(D.TUTAR)
		) AS TUTAR
INTO #TMPTBL FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE
	M.KASANO	= @KASANO AND
	M.TARIH	>= @ILKTARIH AND
	M.TARIH	<= @SONTARIH AND
	M.TIP IN (0,1,2) AND
	D.TIP IN ('SAT', 'IPT')
GROUP BY D.BARKOD, D.STOKADI
ORDER BY SUM(D.TUTAR) DESC

SELECT @ILKTARIH AS ILKTARIH, @SONTARIH AS SONTARIH, BARKOD, STOKADI, MIKTAR, CASE WHEN MIKTAR = 0 THEN 0 ELSE TUTAR / MIKTAR END AS FIYAT, TUTAR
FROM #TMPTBL
WHERE MIKTAR <> 0

DROP TABLE #TMPTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_BEKLETME_MAIN_DELETE]
	@ID INT
AS
	SET NOCOUNT ON

	DELETE FROM TBL_BEKLETME_MAIN
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_BEKLETME_LOG_INSERT]
	@FISID			INT,
	@ACIKLAMA		VARCHAR(MAX),
	@TIP			VARCHAR(3)
AS
	SET NOCOUNT ON

	INSERT INTO TBL_BEKLETME_LOG(FISID, ACIKLAMA, TIP)
	SELECT @FISID, @ACIKLAMA, @TIP
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_BEKLETME_DETAY]
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_BEKLETME_MAIN WITH (NOLOCK)


	SELECT * FROM TBL_BEKLETME_DETAY WITH (NOLOCK)
	WHERE FISID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[PR_BEKLETME_LOG]
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_BEKLETME_MAIN WITH (NOLOCK)


	SELECT * FROM TBL_BEKLETME_LOG WITH (NOLOCK)
	WHERE FISID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[PR_BEKLETME_MAIN]
	@ID	INT = NULL
AS

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_BEKLETME_MAIN WITH (NOLOCK)


	SELECT *, BELGEKODU AS FISBARKOD FROM TBL_BEKLETME_MAIN WITH (NOLOCK)
	WHERE ID = @ID
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_FIS_ADET_KONTROL]
	@KASANO	INT = 1,
	@ADET	INT = 1450
AS

DECLARE 
	@TARIH DATETIME, @FISADEDI	INT

SELECT TOP 1 @TARIH = TARIH
FROM TBL_XZ_LOG WITH (NOLOCK)
WHERE TIP = 'Z'
ORDER BY TARIH DESC

SET @TARIH = ISNULL(@TARIH, GETDATE()-365)

SELECT
	@FISADEDI = COUNT(*)
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.KASANO = @KASANO AND M.TARIH >= @TARIH 

SET @FISADEDI = ISNULL(@FISADEDI,0)

IF @FISADEDI < @ADET 
	SELECT 1 AS DURUM
ELSE 
	SELECT 0 AS DURUM
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_DOVIZ_LIST]
AS
	SELECT * FROM TBL_DOVIZ WHERE DOVIZKODU <> 'TL' ORDER BY ID 
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[SP_IMPORT_DOVIZ_FILE]
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRY
	SELECT
		RTRIM(SUBSTRING(DATA,1,8)) AS DOVIZKODU,
		CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,10,9),'.',''))/10000 AS DOVIZKURU
	INTO #TEMPFILE FROM TBL_IMPORT_FILE
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : DOVIZ DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

BEGIN TRAN

	DELETE FROM TBL_DOVIZ

	BEGIN TRY
		INSERT INTO TBL_DOVIZ(DOVIZKODU, DOVIZKURU, CHANGEDATE)
		SELECT DOVIZKODU, DOVIZKURU, GETDATE() FROM #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_DOVIZ TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

DROP TABLE #TEMPFILE

COMMIT TRAN
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_IMPORT_FILE]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_IMPORT_FILE]
GO
CREATE PROCEDURE PR_IMPORT_FILE
AS
	SELECT * FROM TBL_IMPORT_FILE
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_IMPORT_FILE_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_IMPORT_FILE_INSERT]
GO
CREATE PROCEDURE SP_IMPORT_FILE_INSERT
	@DATA VARCHAR(MAX)
AS
	INSERT INTO TBL_IMPORT_FILE(DATA)
	SELECT @DATA
GO

INSERT INTO TBL_YETKI_TIP(TIP, YETKIID, AKTIF, MOBIL)
SELECT 'A', Z.YETKIID, 1, 1 FROM TBL_YETKI_TIP Z WITH (NOLOCK)
	LEFT JOIN (SELECT ID, YETKIID FROM TBL_YETKI_TIP WITH (NOLOCK) WHERE TIP = 'A') AS A ON A.YETKIID = Z.YETKIID
WHERE A.ID IS NULL AND Z.TIP = 'Z' 
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_USER_MAIN') AND name='KASIYERSIFRESI')
ALTER TABLE dbo.TBL_USER_MAIN ADD
	KASIYERSIFRESI varchar(20) NULL
GO

UPDATE TBL_USER_MAIN
SET KASIYERSIFRESI = PASSWORD
WHERE KASIYERSIFRESI IS NULL
GO

ALTER PROCEDURE [dbo].[SP_IMPORT_KASIYER_FILE]
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

CREATE TABLE #TEMPFILE(USERCODE INT, USERNAME VARCHAR(20), PASSWORD VARCHAR(20), YETKI VARCHAR(1), YUZDE DECIMAL(4,2), TUTAR DECIMAL(21,6))

BEGIN TRY
	INSERT INTO #TEMPFILE(USERCODE, USERNAME, PASSWORD, YETKI, YUZDE, TUTAR)
	SELECT
		CONVERT(INT, SUBSTRING(DATA,2,4)) AS USERCODE,
		RTRIM(SUBSTRING(DATA,6,20)) AS USERNAME,
		LTRIM(RTRIM(SUBSTRING(DATA,26,6))) AS PASSWORD,
		SUBSTRING(DATA,32,1) AS YETKI,
		CONVERT(DECIMAL(4,2), SUBSTRING(DATA,33,2)) AS YUZDE,
		CONVERT(DECIMAL(21,6), SUBSTRING(DATA,35,10))/100 AS TUTAR
	FROM TBL_IMPORT_FILE 
	WHERE LEN(DATA) <= 44
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : KASİYER DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

BEGIN TRY
	INSERT INTO #TEMPFILE(USERCODE, USERNAME, PASSWORD, YETKI, YUZDE, TUTAR)
	SELECT
		CONVERT(INT, SUBSTRING(DATA,2,4)) AS USERCODE,
		RTRIM(SUBSTRING(DATA,6,20)) AS USERNAME,
		LTRIM(RTRIM(SUBSTRING(DATA,26,20))) AS PASSWORD,
		SUBSTRING(DATA,46,1) AS YETKI,
		CONVERT(DECIMAL(4,2), SUBSTRING(DATA,47,2)) AS YUZDE,
		CONVERT(DECIMAL(21,6), SUBSTRING(DATA,49,10))/100 AS TUTAR
	FROM TBL_IMPORT_FILE 
	WHERE LEN(DATA) >= 45
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : KASİYER DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

BEGIN TRAN

	DELETE TBL_USER_MAIN
	WHERE ID > 1

	BEGIN TRY
		INSERT INTO TBL_USER_MAIN(USERCODE, USERNAME, YETKI, ADMIN, PASSWORD, KASIYERSIFRESI, CREATEDATE, YUZDEINDIRIMLIMITI, TUTARINDIRIMLIMITI)
		SELECT USERCODE, USERNAME, YETKI, CASE WHEN YETKI = 'A' THEN 1 ELSE 0 END, SUBSTRING(PASSWORD,1,6), PASSWORD, GETDATE(), YUZDE, TUTAR FROM #TEMPFILE
		WHERE USERCODE NOT IN (SELECT USERCODE FROM TBL_USER_MAIN WITH (NOLOCK))
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_USER_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

DROP TABLE #TEMPFILE

COMMIT TRAN
GO

ALTER PROCEDURE [dbo].[SP_USER_MAIN_LIST]
	@ID		  INT = NULL,
	@USERCODE VARCHAR(100) = NULL,
	@PASSWORD VARCHAR(20) = NULL,
	@USERNAME VARCHAR(50) = NULL
AS
	IF @ID IS NOT NULL
		SELECT
			ID,
			USERCODE,
			USERNAME,
			YETKI,
			ADMIN,
			KASIYERSIFRESI AS PASSWORD,
			YUZDEINDIRIMLIMITI,
			TUTARINDIRIMLIMITI
		FROM TBL_USER_MAIN WITH (NOLOCK)
		WHERE ID = @ID
	ELSE IF @USERNAME IS NOT NULL
		SELECT
			ID,
			USERCODE,
			USERNAME,
			YETKI,
			ADMIN,
			KASIYERSIFRESI AS PASSWORD,
			YUZDEINDIRIMLIMITI,
			TUTARINDIRIMLIMITI
		FROM TBL_USER_MAIN WITH (NOLOCK)
		WHERE
			USERNAME LIKE ISNULL('%'+@USERNAME+'%', USERNAME) 
		ORDER BY USERNAME
	ELSE
		SELECT
			ID,
			USERCODE,
			USERNAME,
			YETKI,
			ADMIN,
			KASIYERSIFRESI AS PASSWORD,
			YUZDEINDIRIMLIMITI,
			TUTARINDIRIMLIMITI
		FROM TBL_USER_MAIN WITH (NOLOCK)
		WHERE
			USERCODE = ISNULL(@USERCODE, USERCODE) AND
			KASIYERSIFRESI = ISNULL(@PASSWORD, KASIYERSIFRESI)
		ORDER BY USERNAME
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_MAIN') AND name='ACIKLAMA')
ALTER TABLE dbo.TBL_BEKLETME_MAIN ADD
	ACIKLAMA varchar(MAX) NULL
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_MAIN_BROWSE]
	@BELGEKODU	VARCHAR(20) = NULL,
	@TARIH		DATETIME = NULL,
	@CARIADI	VARCHAR(50) = NULL,
	@TUTAR		FLOAT = NULL,
	@ACIKLAMA	VARCHAR(MAX) = NULL
AS
	SELECT
		B.ID,
		B.BELGEKODU,
		B.TARIH,
		B.CARIADI,
		B.TUTAR,
		ISNULL(B.ACIKLAMA,'') AS ACIKLAMA
	FROM TBL_BEKLETME_MAIN B WITH (NOLOCK)
	WHERE
		B.ISBEKLETME = 1 AND
		B.BELGEKODU LIKE ISNULL('%'+@BELGEKODU+'%', B.BELGEKODU) AND
		B.TARIH = ISNULL(@TARIH, B.TARIH) AND
		B.CARIADI LIKE ISNULL('%'+@CARIADI+'%', B.CARIADI) AND
		B.TUTAR = ISNULL(@TUTAR, B.TUTAR) AND
		ISNULL(B.ACIKLAMA,'') LIKE ISNULL('%'+@ACIKLAMA+'%', ISNULL(B.ACIKLAMA,'')) 
	ORDER BY TARIH DESC
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_MAIN_LIST]
	@ID	INT = NULL,
	@ISBEKLETME BIT = NULL,
	@BELGEKODU VARCHAR(20) = NULL
AS

	SELECT
		B.ID,
		B.ISBEKLETME,
		B.KASANO,
		B.BELGEKODU,
		B.TARIH,
		B.TIP,
		B.VERGINO,
		B.CARIKODU,
		B.CARIADI,
		ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
		B.TUTAR,
		B.INDYUZDE,
		B.INDTUTAR,
		B.ARTYUZDE,
		B.ARTTUTAR,
		B.KASIYERKODU,
		B.KASIYERADI,
		B.ISEFATURA,
		B.ALIAS,
		B.YETKILIKODU,
		B.YETKILIADI,
		B.OKCNO,
		ISNULL(C.ISVERESIYE,0) AS ISVERESIYE,
		ISNULL(B.ACIKLAMA,'') AS ACIKLAMA
	FROM TBL_BEKLETME_MAIN B WITH (NOLOCK)
		LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = B.CARIKODU
	WHERE
		B.ID = ISNULL(@ID, B.ID) AND
		B.ISBEKLETME = ISNULL(@ISBEKLETME, B.ISBEKLETME) AND
		B.BELGEKODU = ISNULL(@BELGEKODU, B.BELGEKODU)
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_MAIN_INSERT_UPDATE]
	@ID				INT = NULL,
	@ISBEKLETME		BIT,
	@KASANO			INT,
	@BELGEKODU		VARCHAR(20),
	@TARIH			DATETIME,
	@TIP			TINYINT,
	@VERGINO		VARCHAR(20),
	@CARIKODU		VARCHAR(20),
	@CARIADI		VARCHAR(50),
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@ISEFATURA		BIT,
	@ALIAS			VARCHAR(MAX),
	@YETKILIKODU	VARCHAR(4) = NULL,
	@YETKILIADI		VARCHAR(20) = NULL,
	@OKCNO			VARCHAR(20) = NULL,
	@ACIKLAMA		VARCHAR(MAX) = NULL
AS
	SET NOCOUNT ON
	IF ISNULL(@ID,0) = 0
	BEGIN
		IF @ISBEKLETME = 0
			IF EXISTS(SELECT TOP 1 ID FROM TBL_BEKLETME_MAIN WITH (NOLOCK) WHERE ISBEKLETME = 0)
			BEGIN
				DELETE FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
			END
	
		INSERT INTO TBL_BEKLETME_MAIN(ISBEKLETME, KASANO, BELGEKODU, TARIH, TIP, VERGINO, CARIKODU, CARIADI, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, ISEFATURA, ALIAS, YETKILIKODU, YETKILIADI, OKCNO, ACIKLAMA)
		SELECT @ISBEKLETME, @KASANO, @BELGEKODU, @TARIH, @TIP, @VERGINO, @CARIKODU, @CARIADI, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @ISEFATURA, @ALIAS, @YETKILIKODU, @YETKILIADI, @OKCNO, @ACIKLAMA

		RETURN @@IDENTITY
	END
	ELSE
	BEGIN
		DELETE FROM TBL_BEKLETME_LOG WHERE FISID = @ID

		UPDATE TBL_BEKLETME_MAIN
		SET
			ISBEKLETME	= @ISBEKLETME	,
			KASANO		= @KASANO		,
			BELGEKODU	= @BELGEKODU	,
			TARIH		= @TARIH		,
			TIP			= @TIP			,
			VERGINO		= @VERGINO		,
			CARIKODU	= @CARIKODU		,
			CARIADI		= @CARIADI		,
			TUTAR		= @TUTAR		,
			INDYUZDE	= @INDYUZDE		,
			INDTUTAR	= @INDTUTAR		,
			ARTYUZDE	= @ARTYUZDE		,
			ARTTUTAR	= @ARTTUTAR		,
			KASIYERKODU	= @KASIYERKODU	,
			KASIYERADI	= @KASIYERADI	,
			ISEFATURA	= @ISEFATURA	,
			ALIAS		= @ALIAS		,
			YETKILIKODU	= @YETKILIKODU	,
			YETKILIADI	= @YETKILIADI	,
			OKCNO		= @OKCNO		,
			ACIKLAMA	= @ACIKLAMA
		WHERE ID = @ID

		RETURN @ID
	END
GO

ALTER PROCEDURE [dbo].[SP_FIS_MAIN_LIST]
	@ID		INT = NULL,
	@FISBARKOD VARCHAR(20) = NULL,
	@ILKTARIH	SMALLDATETIME = NULL,
	@SONTARIH	SMALLDATETIME = NULL,
	@ISSEND		BIT = NULL,
	@ISHARICI	BIT = NULL
AS
	CREATE TABLE #RETTABLE(
		ID INT, KASANO INT, BELGEKODU VARCHAR(20), TARIH DATETIME, TIP TINYINT, VERGINO VARCHAR(20), CARIKODU VARCHAR(20), CARIADI VARCHAR(50), TUTAR FLOAT, 
		INDYUZDE FLOAT, INDTUTAR FLOAT, ARTYUZDE FLOAT, ARTTUTAR FLOAT, KASIYERKODU VARCHAR(4), KASIYERADI VARCHAR(50), PARAUSTU FLOAT, ISEFATURA BIT, FIYATTIPNO INT, 
		EFATURAKODU VARCHAR(20), UUID VARCHAR(50), TYPE VARCHAR(20), ALIAS VARCHAR(200), YETKILIKODU VARCHAR(4), YETKILIADI VARCHAR(50),
		ACIKLAMA VARCHAR(MAX)
	)

	IF @ID IS NOT NULL
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
 		WHERE F.ID = @ID
	ELSE IF @FISBARKOD IS NOT NULL
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE SUBSTRING(CONVERT(VARCHAR, F.TARIH, 112)+REPLACE(CONVERT(VARCHAR, F.TARIH, 114),':',''),1,14) = SUBSTRING(@FISBARKOD,1,14)
	ELSE IF ISNULL(@ISSEND,1) = 0
	BEGIN
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE 
			((ISSEND IS NULL OR ISSEND = 0) OR (@ISHARICI = 1)) AND
			CONVERT(VARCHAR, F.TARIH, 112) >= CONVERT(VARCHAR, @ILKTARIH, 112) AND
			CONVERT(VARCHAR, F.TARIH, 112) <= CONVERT(VARCHAR, @SONTARIH, 112) 
	END
	ELSE
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE 
			CONVERT(VARCHAR, F.TARIH, 112) >= CONVERT(VARCHAR, @ILKTARIH, 112) AND
			CONVERT(VARCHAR, F.TARIH, 112) <= CONVERT(VARCHAR, @SONTARIH, 112) 
		
	UPDATE #RETTABLE
	SET TYPE = E.TYPE
	FROM #RETTABLE R
		INNER JOIN TBL_CARI_EFATURA E WITH (NOLOCK) ON E.ALIAS = R.ALIAS
	WHERE R.ISEFATURA = 1

	SELECT * FROM #RETTABLE
	ORDER BY ID ASC

	DROP TABLE #RETTABLE
GO

ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R1]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	CREATE TABLE #REYONPROMOSYON(PROMOSYONID INT, REYONADI VARCHAR(20), AMIKTAR DECIMAL(21,6), VMIKTAR DECIMAL(21,6), INDYUZDE FLOAT, INDTUTAR FLOAT)
	
	INSERT INTO #REYONPROMOSYON(PROMOSYONID, REYONADI, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
	SELECT 
		P.ID,
		REYONADI,
		AMIKTAR, 
		VMIKTAR,
		INDYUZDE,
		INDTUTAR
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R1' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 
	
	IF EXISTS(SELECT TOP 1 * FROM #REYONPROMOSYON)
	BEGIN
		CREATE TABLE #INDIRIM(AREYONADI VARCHAR(20), INDIRIMTUTARI FLOAT, AMIKTAR FLOAT, VMIKTAR FLOAT)

		CREATE TABLE #FIS(
							ID INT IDENTITY(1,1) PRIMARY KEY,
							PROMOSYONID INT,
							REYONADI VARCHAR(20), 
							ASATISFIYAT FLOAT, 
							ASATISMIKTAR FLOAT, 
							ASATISTUTAR FLOAT, 
							AMIKTAR FLOAT, 
							VMIKTAR FLOAT, 
							INDYUZDE FLOAT, 
							INDTUTAR FLOAT
						)
		
		DECLARE
			@ID					INT, 
			@AREYONADI			VARCHAR(20),

			@ASATISFIYAT		FLOAT, 
			@ASATISMIKTAR		FLOAT, 
			@ASATISTUTAR		FLOAT, 

			@ALINACAKMIKTAR		FLOAT, 
			@VERILECEKMIKTAR	FLOAT, 
			@AKALANMIKTAR		FLOAT,
			@R1INDYUZDE			FLOAT,
			@R1INDTUTAR			FLOAT


		INSERT INTO #FIS(PROMOSYONID, REYONADI, ASATISFIYAT, ASATISMIKTAR, ASATISTUTAR,  AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
		SELECT 
			P.PROMOSYONID,
			S.REYONADI,
			D.FIYAT,
			SUM(D.MIKTAR) AS MIKTAR,
			SUM(D.TUTAR) AS TUTAR,
			P.AMIKTAR,
			P.VMIKTAR,
			P.INDYUZDE,
			P.INDTUTAR
		FROM TBL_BEKLETME_DETAY D
			INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
			INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) S ON S.PLUNO = D.PLUNO
			INNER JOIN #REYONPROMOSYON P ON P.REYONADI COLLATE TURKISH_CI_AS = S.REYONADI 
		WHERE ISBEKLETME = 0
		GROUP BY P.PROMOSYONID, S.REYONADI, D.FIYAT, P.AMIKTAR, P.VMIKTAR, P.INDYUZDE, P.INDTUTAR
		HAVING SUM(D.MIKTAR) > 0
		ORDER BY FIYAT DESC
		
		DECLARE @PROMOSYONID INT
		DECLARE CURRREYON CURSOR FAST_FORWARD FOR
		SELECT PROMOSYONID FROM #FIS
		GROUP BY PROMOSYONID
		OPEN CURRREYON
		
		FETCH NEXT FROM CURRREYON
		INTO @PROMOSYONID

		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @AKALANMIKTAR = 0

			DECLARE CURR CURSOR FAST_FORWARD FOR
			SELECT 
				ID,
				REYONADI,
				ASATISFIYAT,
				ASATISMIKTAR,
				ASATISTUTAR,
				AMIKTAR,
				VMIKTAR,
				CASE WHEN INDYUZDE <= 0 THEN 100 ELSE INDYUZDE END,
				INDTUTAR
			FROM #FIS
			WHERE PROMOSYONID = @PROMOSYONID
			ORDER BY ASATISFIYAT DESC
			OPEN CURR

			FETCH NEXT FROM CURR
			INTO 
				@ID					,
				@AREYONADI			,
				@ASATISFIYAT		,
				@ASATISMIKTAR		,
				@ASATISTUTAR		,
				@ALINACAKMIKTAR		,
				@VERILECEKMIKTAR	,
				@R1INDYUZDE,
				@R1INDTUTAR

			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @AKALANMIKTAR = @AKALANMIKTAR + @ASATISMIKTAR

				WHILE @AKALANMIKTAR >= @ALINACAKMIKTAR 
				BEGIN
					INSERT INTO #INDIRIM(AREYONADI, INDIRIMTUTARI, AMIKTAR, VMIKTAR)
					SELECT @AREYONADI, CASE WHEN @R1INDTUTAR > 0 THEN @R1INDTUTAR ELSE ROUND(((@VERILECEKMIKTAR * @ASATISFIYAT) * @R1INDYUZDE / 100.00),2) END , @ALINACAKMIKTAR, @VERILECEKMIKTAR

					SET @AKALANMIKTAR = @AKALANMIKTAR - @ALINACAKMIKTAR
				END
	
				FETCH NEXT FROM CURR
				INTO 
					@ID					,
					@AREYONADI			,
					@ASATISFIYAT		,
					@ASATISMIKTAR		,
					@ASATISTUTAR		,
					@ALINACAKMIKTAR		,
					@VERILECEKMIKTAR	,
					@R1INDYUZDE,
					@R1INDTUTAR

			END

			CLOSE CURR
			DEALLOCATE CURR
			
			FETCH NEXT FROM CURRREYON
			INTO @PROMOSYONID
		END

		CLOSE CURRREYON
		DEALLOCATE CURRREYON

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT 
			'25',
			0,
			SUM(INDIRIMTUTARI) AS INDIRIMTUTARI,
			SUBSTRING(AREYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, SUM(AMIKTAR))+' ADET ALANA '+CONVERT(VARCHAR, SUM(VMIKTAR))+' ADET ÜRÜNDE '+CONVERT(VARCHAR, CAST(ROUND(SUM(INDIRIMTUTARI),2) AS MONEY),1)+' TL İNDİRİM',
			0
		FROM #INDIRIM
		GROUP BY AREYONADI

		DROP TABLE #FIS
		DROP TABLE #INDIRIM		
	END


	
	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #REYONPROMOSYON
	DROP TABLE #RETTABLE
GO

ALTER PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_IBM_KONTROL] 
	@CARITIPI		VARCHAR(1) ,
	@ARATOPLAM		FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 


DECLARE @NOBONUSTUTAR FLOAT

SELECT @NOBONUSTUTAR = SUM(TUTAR) 
FROM TBL_BEKLETME_DETAY
WHERE FISID IN (
				SELECT ID FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
				) AND
BARKOD IN (SELECT BARKOD FROM TBL_STOK_MAIN WHERE ISNULL(REYONADI,'') = 'NOBONUS'  OR (ISNULL(ISINDIRIM,1) = 0))

SET @NOBONUSTUTAR = ISNULL(@NOBONUSTUTAR,0)

SET @ARATOPLAM = @ARATOPLAM - @NOBONUSTUTAR

DECLARE @CARIGRUP VARCHAR(20)

IF ISNULL(@CARIKODU,'') <> ''
	SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

SET @CARIGRUP = ISNULL(@CARIGRUP,'')


IF @CARITIPI = 'M' SET @CARITIPI = NULL

	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		'15' AS INDIRIMTIPI,
		0,
		ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
		CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.STOKKODU, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.STOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
	WHERE 
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		CARIGRUP = @CARIGRUP AND
		VREYONADI = '' AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) > 1  AND
		D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '15')
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			'15' AS INDIRIMTIPI,
			0,
			ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
			CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.STOKKODU, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.STOKKODU
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
		WHERE 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			CARIGRUP = '' AND
			VREYONADI = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) > 1  AND
			D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
		CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END,
		CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
		CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
			CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
		ELSE
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		END
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @ARATOPLAM AND 
		CARIGRUP = @CARIGRUP AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		PUAN = 0 AND
		ISNULL(PUANYUZDE,0) = 0
	ORDER BY ARATOPLAM DESC
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('05','07'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN END)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			CARIGRUP = '' AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			PUAN = 0 AND
			ISNULL(PUANYUZDE,0) = 0
		ORDER BY ARATOPLAM DESC
	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		TOP 1
		'09',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2)		
		 AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 0
	ORDER BY U.ARATOPLAM DESC
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'09',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
		((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END,2)		
		 AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 1
	ORDER BY U.ARATOPLAM ASC
		
		
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('09'))
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			TOP 1
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
							GROUP BY S.STOKKODU
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.STOKKODU = U.VSTOKKODU AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.VSTOKKODU
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 1
		ORDER BY U.ARATOPLAM ASC
	
	END

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'10',
		0,
		U.INDTUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(U.INDTUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR >  ISNULL(@INDTUTAR,0)
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('10'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'10',
			0,
			U.INDTUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(U.INDTUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR >  ISNULL(@INDTUTAR,0)
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'11',
		0,
		D.TUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		U.CARIGRUP = @CARIGRUP AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR = 0 AND
		U.INDYUZDE = 0 
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'11',
			0,
			D.TUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR = 0 AND
			U.INDYUZDE = 0 
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
		0,
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
		CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN
	FROM (
			SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
			GROUP BY S.STOKKODU
			HAVING SUM(MIKTAR) > 0
		) AS D 
		INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.STOKKODU = D.STOKKODU AND A.STOKKODU = A.VSTOKKODU AND A.CARIGRUP = @CARIGRUP
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = A.STOKKODU
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0	AND
		A.VMIKTAR <> 0	
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('14','16'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT 
			CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
			0,
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
			CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN
		FROM (
				SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
				FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
					INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
					INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD 
				GROUP BY S.STOKKODU
				HAVING SUM(MIKTAR) > 0
			) AS D 
			INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.STOKKODU = D.STOKKODU AND A.STOKKODU = A.VSTOKKODU AND A.CARIGRUP = ''
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = A.STOKKODU
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0 AND
			A.VMIKTAR <> 0	
	
	CREATE TABLE #PROMOSYONTBL(ASTOKKODU VARCHAR(20), VSTOKKODU VARCHAR(20), VREYONADI VARCHAR(20)  COLLATE TURKISH_CI_AS, AMIKTAR FLOAT, VMIKTAR FLOAT, ALINANMIKTAR FLOAT, VERILENMIKTAR FLOAT, VERILENBIRIMFIYAT FLOAT, PUAN FLOAT, SATIR INT, INDYUZDE FLOAT, INDTUTAR FLOAT)		

	INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT STOKKODU, VSTOKKODU, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.CARIGRUP = @CARIGRUP AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
		A.STOKKODU <> A.VSTOKKODU 
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 1)
		INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT STOKKODU, VSTOKKODU, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.CARIGRUP = '' AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.STOKKODU <> A.VSTOKKODU 
		
	INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT STOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P2' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
		A.CARIGRUP = @CARIGRUP AND
		ISNULL(VREYONADI,'') <> ''

	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 2)
		INSERT INTO #PROMOSYONTBL(ASTOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT STOKKODU, VSTOKKODU, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P2' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.CARIGRUP = '' AND
			ISNULL(VREYONADI,'') <> ''

	UPDATE #PROMOSYONTBL
	SET	VSTOKKODU = H.STOKKODU
	FROM #PROMOSYONTBL P
		INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.REYONADI  COLLATE TURKISH_CI_AS = P.VREYONADI
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) H ON H.STOKKODU = S.STOKKODU
	WHERE P.VREYONADI <> ''
	
	UPDATE #PROMOSYONTBL
	SET ALINANMIKTAR = H.MIKTAR
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) H ON H.STOKKODU = P.ASTOKKODU

	UPDATE #PROMOSYONTBL
	SET VERILENMIKTAR = H.MIKTAR,
		VERILENBIRIMFIYAT = CASE WHEN VERILENBIRIMFIYAT > 0 THEN VERILENBIRIMFIYAT ELSE H.BIRIMFIYAT END
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) H ON H.STOKKODU = P.VSTOKKODU

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'18',
		0,
		(CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								((CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END)) 
								AS MONEY
							)		 
						,1)
		+' TL İND',
		FLOOR(ALINANMIKTAR / AMIKTAR) * PUAN
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS A ON A.STOKKODU = P.ASTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS V ON V.STOKKODU = P.VSTOKKODU
	WHERE 
		VMIKTAR = 0 AND
		ALINANMIKTAR <> 0 AND 
		VERILENMIKTAR <> 0 AND
		FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, A.STOKADI, INDYUZDE, INDTUTAR  	
	
	DELETE FROM #PROMOSYONTBL
	WHERE VMIKTAR = 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'17',
		0,
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								CASE 
									WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
										THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
										ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
									ELSE 0 
								END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END) AS MONEY
							)		 
						,1)
		+' TL İND',
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * PUAN
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS A ON A.STOKKODU = P.ASTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS V ON V.STOKKODU = P.VSTOKKODU
	WHERE ALINANMIKTAR <> 0 AND VERILENMIKTAR <> 0 AND
		(CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END)) <> 0
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, A.STOKADI, INDYUZDE  	
		

	DROP TABLE #PROMOSYONTBL

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '28' ELSE '29' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, FLOOR(H.MIKTAR / P.AMIKTAR) * P.AMIKTAR)+' ADET ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM = 0 AND
		P.AMIKTAR > 0 AND
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) > 0 AND
		ISKADEMELI = 0
		

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.STOKKODU, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
						HAVING SUM(MIKTAR) > 0
					) L ON L.STOKKODU = P.VSTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = L.STOKKODU
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.VMIKTAR * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
						HAVING SUM(MIKTAR) > 0
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.STOKKODU, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
						GROUP BY S.STOKKODU
					) L ON L.STOKKODU = P.VSTOKKODU
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = L.STOKKODU
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		0,
		CASE 
			WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
		ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
		END,
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, (FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR))+' ADET ALANA '+
		CONVERT(VARCHAR, CAST( 
								CASE 
									WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
								ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
								END		
							AS MONEY), 1)+' TL İND.',
		(FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.MIKTAR) AS MIKTAR, MIN(D.FIYAT) AS FIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		AMIKTAR <> 0 AND 
		VMIKTAR <> 0 AND 
		H.MIKTAR >= AMIKTAR AND
		ISKADEMELI = 0 AND
		ARATOPLAM = 0 AND
		(
			(P.INDYUZDE <> 0) OR
			(P.INDTUTAR <> 0)
		)
		 
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'26',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN H.MIKTAR * INDTUTAR ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN ALDIĞINIZ ÜRÜNLER İÇİN '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN H.MIKTAR * INDTUTAR ELSE (H.TUTAR * INDYUZDE) / 100.00  END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		P.CARIGRUP = @CARIGRUP AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 1 AND 
		VMIKTAR = 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	IF EXISTS(
				SELECT TOP 1 1 FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
				INNER JOIN (
								SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
								FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
									INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
									INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
								GROUP BY S.REYONADI
							) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
				WHERE 
					P.BASLANGICTARIHI <= GETDATE() AND
					P.BITISTARIHI >= GETDATE() AND
					P.PROMOSYONTIPI = 'P7' AND 
					P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
					P.CARIGRUP = @CARIGRUP AND
					P.REYONADI <> '' AND 
					VPLUNO = 0 AND 
					H.TUTAR >= ARATOPLAM AND
					ISKADEMELI = 1
			)
	BEGIN
		DECLARE @REYONADI		VARCHAR(20),
				@REYONINDYUZDE	FLOAT,
				@REYONINDTUTAR	FLOAT,
				@STOKSTOKKODU	VARCHAR(20),
				@STOKMIKTAR		FLOAT,
				@STOKFIYAT		FLOAT,
				@ADET			FLOAT
				
		
		CREATE TABLE #STABLE(ID INT IDENTITY(1,1) PRIMARY KEY, STOKKODU VARCHAR(20), FIYAT FLOAT, INDTUTAR FLOAT, SIRANO INT)

		DECLARE CURREYON CURSOR FAST_FORWARD FOR
		SELECT P.REYONADI, P.INDYUZDE, P.INDTUTAR FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN AS S ON S.BARKOD = D.BARKOD
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		WHERE 
			P.BASLANGICTARIHI <= GETDATE() AND
			P.BITISTARIHI >= GETDATE() AND
			P.PROMOSYONTIPI = 'P7' AND 
			P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
			P.CARIGRUP = @CARIGRUP AND
			P.REYONADI <> '' AND 
			VPLUNO = 0 AND 
			H.TUTAR >= ARATOPLAM AND
			ISKADEMELI = 1
		OPEN CURREYON
		
		FETCH NEXT FROM CURREYON
		INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE FROM #STABLE	
			
			DECLARE CURRSTOK CURSOR FAST_FORWARD FOR
			SELECT S.STOKKODU, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) / SUM(MIKTAR) AS FIYAT
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.BARKOD = D.BARKOD
			WHERE S.REYONADI = @REYONADI 
			GROUP BY S.STOKKODU
			HAVING (SUM(MIKTAR) <> 0) AND (SUM(MIKTAR) - FLOOR(SUM(MIKTAR)) = 0)
			OPEN CURRSTOK
			
			FETCH NEXT FROM CURRSTOK
			INTO @STOKSTOKKODU, @STOKMIKTAR, @STOKFIYAT
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ADET = @STOKMIKTAR
				
				WHILE @ADET > 0 
				BEGIN
					INSERT INTO #STABLE(STOKKODU, FIYAT, INDTUTAR, SIRANO)
					SELECT @STOKSTOKKODU, @STOKFIYAT, CASE WHEN @REYONINDYUZDE = 0 THEN @REYONINDTUTAR ELSE ROUND((@STOKFIYAT * @REYONINDYUZDE) / 100.00,2) END, 0
					
					SET @ADET = @ADET - 1
				END
			
				FETCH NEXT FROM CURRSTOK
				INTO @STOKSTOKKODU, @STOKMIKTAR, @STOKFIYAT
			END
			
			CLOSE CURRSTOK
			DEALLOCATE CURRSTOK
			
			UPDATE #STABLE
			SET SIRANO = H.SIRANO
			FROM #STABLE S
				INNER JOIN (SELECT ID, ROW_NUMBER() OVER(ORDER BY FIYAT DESC) AS SIRANO FROM #STABLE) AS H ON H.ID = S.ID
			
			DELETE FROM #STABLE 
			WHERE SIRANO % 2 <> 0

			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
			SELECT 
				'30',
				@REYONINDYUZDE,
				ROUND(INDTUTAR,2),
				SUBSTRING(M.STOKADI,1,20)+' KADEMELİ '+CONVERT(VARCHAR, CAST(INDTUTAR AS MONEY), 1)+' TL İND.',
				0
			FROM #STABLE S
				INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY STOKKODU, STOKADI) AS M ON M.STOKKODU = S.STOKKODU
			WHERE INDTUTAR <> 0
			ORDER BY INDTUTAR DESC
			
			FETCH NEXT FROM CURREYON
			INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		END
		
		CLOSE CURREYON
		DEALLOCATE CURREYON		
		
		DROP TABLE #STABLE
	END
	
	DECLARE @TOPLAMINDIRIM FLOAT
	
	SELECT @TOPLAMINDIRIM  = SUM(INDTUTAR) FROM #RETTABLE
	
	SET @ARATOPLAM = @ARATOPLAM - ABS(ISNULL(@TOPLAMINDIRIM,0))
	
	IF @ARATOPLAM > 0
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			'27',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
				END
			END,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, 
								CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
									CASE 
										WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
										ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
									END
								END
				)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			CARIGRUP = @CARIGRUP AND
			(
				PUAN > 0 OR
				ISNULL(PUANYUZDE,0) > 0
			) AND
			INDYUZDE = 0 AND
			INDTUTAR = 0
		ORDER BY ARATOPLAM DESC
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '27')
			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
			SELECT  
				TOP 1
				'27',
				INDYUZDE,
				ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
				CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
					CASE 
						WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
						ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
					END
				END,
				CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
				CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
					CONVERT(VARCHAR, 
									CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
										CASE 
											WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
											ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
										END
									END
					)+' PUAN'
				ELSE
					CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
				END
			FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			WHERE 
				ARATOPLAM <= @ARATOPLAM AND 
				BASLANGICTARIHI <= GETDATE() AND
				BITISTARIHI >= GETDATE() AND
				PROMOSYONTIPI = 'P1' AND 
				CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
				CARIGRUP = '' AND
				(
					PUAN > 0 OR
					ISNULL(PUANYUZDE,0) > 0
				) AND
				INDYUZDE = 0 AND
				INDTUTAR = 0
			ORDER BY ARATOPLAM DESC
		
	END

	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

ALTER PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_KONTROL] 
	@CARITIPI		VARCHAR(1) ,
	@ARATOPLAM		FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 


DECLARE @NOBONUSTUTAR FLOAT

SELECT @NOBONUSTUTAR = SUM(TUTAR) 
FROM TBL_BEKLETME_DETAY
WHERE FISID IN (
				SELECT ID FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
				) AND
PLUNO IN (SELECT PLUNO FROM TBL_STOK_MAIN WHERE ISNULL(REYONADI,'') = 'NOBONUS'  OR (ISNULL(ISINDIRIM,1) = 0)) 

SET @NOBONUSTUTAR = ISNULL(@NOBONUSTUTAR,0)

SET @ARATOPLAM = @ARATOPLAM - @NOBONUSTUTAR

DECLARE @CARIGRUP VARCHAR(255)

IF ISNULL(@CARIKODU,'') <> ''
	SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

SET @CARIGRUP = ISNULL(@CARIGRUP,'')

IF @CARITIPI = 'M' SET @CARITIPI = NULL

	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)
	
	IF @CARIGRUP = 'NOBONUS' 
	BEGIN
		SELECT * FROM #RETTABLE
	
		DROP TABLE #RETTABLE
		
		RETURN
	END
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA, PLUNO)
	SELECT  
		'15' AS INDIRIMTIPI,
		0,
		ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
		CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM',
		U.PLUNO
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.PLUNO 
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
	WHERE 
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		(
			CARIGRUP = @CARIGRUP OR
			CARIGRUP = ''
		) AND
		VREYONADI = '' AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) > 1  AND
		D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '15')
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA, PLUNO)
		SELECT  
			'15' AS INDIRIMTIPI,
			0,
			ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
			CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM',
			U.PLUNO
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.PLUNO 
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
		WHERE 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			CARIGRUP = '' AND
			VREYONADI = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) > 1  AND
			D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
		0,
		CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
		CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @ARATOPLAM AND 
		(
			CARIGRUP = @CARIGRUP OR
			CARIGRUP = ''
		) AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		PUAN = 0 AND
		ISNULL(PUANYUZDE,0) = 0
	ORDER BY ARATOPLAM DESC
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('05','07'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			0,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			CARIGRUP = '' AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			PUAN = 0 AND
			ISNULL(PUANYUZDE,0) = 0
		ORDER BY ARATOPLAM DESC
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT  
		TOP 1
		'09',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * (INDTUTAR) ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * (INDTUTAR) ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2)		
		 AS MONEY), 1)+' TL İND.',
		PUAN,
		U.VPLUNO
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT PLUNO, STOKADI, FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, FIYAT) AS S ON S.PLUNO = U.VPLUNO
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 0
	ORDER BY U.ARATOPLAM DESC


	SELECT 
		STOKADI,
		ARATOPLAM,
		INDYUZDE,
		INDTUTAR,
		VMIKTAR,
		D.MIKTAR AS SATILANMIKTAR,
		D.TUTAR AS SATILANFIYAT,
		D.TOPTUTAR AS SATILANTUTAR,
		FLOOR(@ARATOPLAM / U.ARATOPLAM) AS KATSAYI,
		VPLUNO
	INTO #TEMP FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 1
	ORDER BY U.ARATOPLAM DESC
	

	DECLARE
		@STOKADI VARCHAR(50), 
		@ARATOP FLOAT, 
		@INDIRIM FLOAT, 
		@VMIKTAR FLOAT, 
		@SATILANMIKTAR FLOAT, 
		@SATILANFIYAT FLOAT, 
		@SATILANTUTAR FLOAT, 
		@KATSAYI INT,
		@TOPARA FLOAT,
		@VPLUNO INT

	DECLARE CURRT CURSOR FAST_FORWARD FOR
	SELECT ARATOPLAM FROM #TEMP
	GROUP BY ARATOPLAM
	OPEN CURRT

	FETCH NEXT FROM CURRT
	INTO @TOPARA

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE CURR CURSOR FAST_FORWARD FOR
		SELECT STOKADI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, SATILANMIKTAR, SATILANFIYAT, SATILANTUTAR, KATSAYI, VPLUNO FROM #TEMP
		WHERE ARATOPLAM = @TOPARA AND SATILANMIKTAR >= VMIKTAR
		ORDER BY INDTUTAR DESC
		OPEN CURR

		FETCH NEXT FROM CURR
		INTO @STOKADI, @ARATOP, @INDYUZDE, @INDTUTAR, @VMIKTAR, @SATILANMIKTAR, @SATILANFIYAT, @SATILANTUTAR, @KATSAYI, @VPLUNO
	
		DECLARE @KALANKATSAYI INT

		SELECT TOP 1 @KALANKATSAYI = KATSAYI FROM #TEMP
		WHERE ARATOPLAM = @TOPARA

		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @KALANKATSAYI <= 0 BREAK
		
			SET @INDIRIM = 0

			IF @INDTUTAR > 0
			BEGIN
			
				IF @KALANKATSAYI >= @SATILANMIKTAR 
				BEGIN
					SET @INDIRIM = @SATILANMIKTAR  * @INDTUTAR
					SET @KALANKATSAYI = @KALANKATSAYI - @SATILANMIKTAR
				END
				ELSE
				BEGIN
					SET @INDIRIM = @KALANKATSAYI * @INDTUTAR
					SET @KALANKATSAYI = 0
					
				END
			END
			ELSE IF @INDYUZDE > 0
			BEGIN
				IF @KALANKATSAYI >= @SATILANMIKTAR
				BEGIN
					SET @INDIRIM = (@SATILANTUTAR * @INDYUZDE) / 100.00
					SET @KALANKATSAYI = @KALANKATSAYI - @SATILANMIKTAR
				END
				ELSE
				BEGIN
					SET @INDIRIM = ((@KALANKATSAYI * @SATILANFIYAT) * @INDYUZDE) / 100.00
					SET @KALANKATSAYI = 0
				END
			END

			IF @INDIRIM > 0
				INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
				SELECT 
					'09', 
					@INDYUZDE, 
					@INDIRIM, 
					CONVERT(VARCHAR, CAST(@ARATOP AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(@STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
					ROUND(@INDIRIM,2) AS MONEY), 1)+' TL İND.',
					0,
					@VPLUNO

			FETCH NEXT FROM CURR
			INTO @STOKADI, @ARATOP, @INDYUZDE, @INDTUTAR, @VMIKTAR, @SATILANMIKTAR, @SATILANFIYAT, @SATILANTUTAR, @KATSAYI, @VPLUNO
		END
	
		CLOSE CURR
		DEALLOCATE CURR

		FETCH NEXT FROM CURRT
		INTO @TOPARA
	END

	CLOSE CURRT
	DEALLOCATE CURRT

	DROP TABLE #TEMP
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('09'))
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT  
			TOP 1
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN,
			VPLUNO
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT  
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN,
			VPLUNO
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 1
		ORDER BY U.ARATOPLAM ASC
	
	END
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'10',
		U.INDYUZDE,
		CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END,
		CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ALIŞVERİŞİNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			U.INDTUTAR > 0 OR
			U.INDYUZDE > 0
		)
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('10'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'10',
			U.INDYUZDE,
			CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END,
			CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+'  REYONU ALIŞVERİŞİNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR  FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				U.INDTUTAR > 0 OR
				U.INDYUZDE > 0
			)
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'11',
		0,
		D.TUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR = 0 AND
		U.INDYUZDE = 0 
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'11',
			0,
			D.TUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR = 0 AND
			U.INDYUZDE = 0 
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
		0,
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
		CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN,
		A.PLUNO
	FROM (
			SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
			GROUP BY PLUNO
			HAVING SUM(MIKTAR) > 0
		) AS D 
		INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.PLUNO = D.PLUNO AND A.PLUNO = A.VPLUNO AND (A.CARIGRUP = @CARIGRUP OR A.CARIGRUP = '')
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = A.PLUNO
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0	AND
		A.VMIKTAR <> 0	
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('14','16'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT 
			CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
			0,
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
			CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN,
			A.PLUNO
		FROM (
				SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
				FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
					INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				GROUP BY PLUNO
				HAVING SUM(MIKTAR) > 0
			) AS D 
			INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.PLUNO = D.PLUNO AND A.PLUNO = A.VPLUNO AND A.CARIGRUP = ''
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = A.PLUNO
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0 AND
			A.VMIKTAR <> 0	
	
	CREATE TABLE #PROMOSYONTBL(APLUNO INT, VPLUNO INT, VREYONADI VARCHAR(20)  COLLATE TURKISH_CI_AS, AMIKTAR FLOAT, VMIKTAR FLOAT, ALINANMIKTAR FLOAT, VERILENMIKTAR FLOAT, VERILENBIRIMFIYAT FLOAT, PUAN FLOAT, SATIR INT, INDYUZDE FLOAT, INDTUTAR FLOAT)		

	INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT PLUNO, VPLUNO, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		(
			A.CARIGRUP = @CARIGRUP OR
			A.CARIGRUP = ''
		) AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
		A.PLUNO <> A.VPLUNO 
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 1)
		INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT PLUNO, VPLUNO, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.CARIGRUP = '' AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.PLUNO <> A.VPLUNO 
		
	INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT PLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P2' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
		(
			A.CARIGRUP = @CARIGRUP OR
			A.CARIGRUP = ''
		) AND
		ISNULL(VREYONADI,'') <> ''

	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 2)
		INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT PLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P2' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.CARIGRUP = '' AND
			ISNULL(VREYONADI,'') <> ''

	UPDATE #PROMOSYONTBL
	SET	VPLUNO = H.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.REYONADI  COLLATE TURKISH_CI_AS = P.VREYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = S.PLUNO
	WHERE P.VREYONADI <> ''
	
	UPDATE #PROMOSYONTBL
	SET ALINANMIKTAR = H.MIKTAR
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = P.APLUNO

	UPDATE #PROMOSYONTBL
	SET VERILENMIKTAR = H.MIKTAR,
		VERILENBIRIMFIYAT = CASE WHEN VERILENBIRIMFIYAT > 0 THEN VERILENBIRIMFIYAT ELSE H.BIRIMFIYAT END
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = P.VPLUNO

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'18',
		0,
		(CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								((CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END)) 
								AS MONEY
							)		 
						,1)
		+' TL İND',
		FLOOR(ALINANMIKTAR / AMIKTAR) * PUAN,
		V.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS A ON A.PLUNO = P.APLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS V ON V.PLUNO = P.VPLUNO
	WHERE 
		VMIKTAR = 0 AND
		ALINANMIKTAR <> 0 AND 
		VERILENMIKTAR <> 0 AND
		FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, V.PLUNO, A.STOKADI, INDYUZDE, INDTUTAR  	
	
	DELETE FROM #PROMOSYONTBL
	WHERE VMIKTAR = 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'17',
		0,
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								CASE 
									WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
										THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
										ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
									ELSE 0 
								END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END) AS MONEY
							)		 
						,1)
		+' TL İND',
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * PUAN,
		V.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS A ON A.PLUNO = P.APLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS V ON V.PLUNO = P.VPLUNO
	WHERE ALINANMIKTAR <> 0 AND VERILENMIKTAR <> 0 AND
		(CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END)) <> 0
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, A.STOKADI, INDYUZDE, V.PLUNO  	
		

	DROP TABLE #PROMOSYONTBL

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		--TOP 1 --MURAT
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND((T.TUTAR * INDYUZDE) / 100.00,2),
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN ÜRÜN ALANA '+CONVERT(VARCHAR, FLOOR(T.TUTAR / ARATOPLAM)*PUAN)+' PUAN HEDİYE',
		FLOOR(T.TUTAR / ARATOPLAM) * PUAN,
		NULL
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR > 0 AND
		ARATOPLAM > 0 AND 
		T.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR = 0 AND
		P.INDYUZDE = 0 AND 
		P.PUAN > 0
	ORDER BY P.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR > 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR > 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND((H.TUTAR * INDYUZDE) / 100.00,2),
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN '+STOKADI+' ALANA '+CONVERT(VARCHAR, CAST(ROUND((H.TUTAR * INDYUZDE) / 100.00,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		H.PLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, S.PLUNO, S.STOKADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.PLUNO, S.STOKADI, S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		T.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDYUZDE > 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		TOP 1
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR > 0
	ORDER BY P.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '28' ELSE '29' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, FLOOR(H.MIKTAR / P.AMIKTAR) * P.AMIKTAR)+' ADET ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM = 0 AND
		P.AMIKTAR > 0 AND
		P.VMIKTAR = 0 AND
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2) > 0 AND
		ISKADEMELI = 0
		

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.VMIKTAR * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		CASE WHEN P.VMIKTAR > L.MIKTAR THEN L.MIKTAR ELSE P.VMIKTAR END *
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(CASE WHEN P.VMIKTAR > L.MIKTAR THEN L.MIKTAR ELSE P.VMIKTAR END * ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR > 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		'25',
		0,
		CASE 
			WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
		ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
		END,
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, (FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR))+' ADET ALANA '+
		CONVERT(VARCHAR, CAST( 
								CASE 
									WHEN P.INDYUZDE > 0 THEN (((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * H.FIYAT) * P.INDYUZDE) / 100.00
								ELSE ((FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * P.INDTUTAR)
								END		
							AS MONEY), 1)+' TL İND.',
		(FLOOR(H.MIKTAR / AMIKTAR) * VMIKTAR) * PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.MIKTAR) AS MIKTAR, MIN(FIYAT) AS FIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		AMIKTAR <> 0 AND 
		VMIKTAR <> 0 AND 
		H.MIKTAR >= AMIKTAR AND
		ISKADEMELI = 0 AND
		ARATOPLAM = 0 AND
		(
			(P.INDYUZDE <> 0) OR
			(P.INDTUTAR <> 0)
		)
		 
	--R1 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R1 @CARITIPI, @CARIGRUP

	--R2 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R2 @CARITIPI, @CARIGRUP

	--R3 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R3 @CARITIPI, @CARIGRUP

	--R4 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R4 @CARITIPI, @CARIGRUP

	--R5 PROMOSYONU ÜRÜN PROMOSYONU OLARAK ALINMIŞTIR

	--R6 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R6 @CARITIPI, @CARIGRUP, @ARATOPLAM

	IF EXISTS(
				SELECT TOP 1 1 FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
				INNER JOIN (
								SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
								FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
									INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
									INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
								GROUP BY S.REYONADI
							) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
				WHERE 
					P.BASLANGICTARIHI <= GETDATE() AND
					P.BITISTARIHI >= GETDATE() AND
					P.PROMOSYONTIPI = 'P7' AND 
					P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
					(
						P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
						ISNULL(P.CARIGRUP,'') = ''
					) AND
					P.REYONADI <> '' AND 
					VPLUNO = 0 AND 
					H.TUTAR >= ARATOPLAM AND
					ISKADEMELI = 1
			)
	BEGIN
		DECLARE @REYONADI		VARCHAR(20),
				@REYONINDYUZDE	FLOAT,
				@REYONINDTUTAR	FLOAT,
				@STOKPLUNO		INT,
				@STOKMIKTAR		FLOAT,
				@STOKFIYAT		FLOAT,
				@ADET			FLOAT
				
		
		CREATE TABLE #STABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PLUNO INT, FIYAT FLOAT, INDTUTAR FLOAT, SIRANO INT)

		DECLARE CURREYON CURSOR FAST_FORWARD FOR
		SELECT P.REYONADI, P.INDYUZDE, P.INDTUTAR FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		WHERE 
			P.BASLANGICTARIHI <= GETDATE() AND
			P.BITISTARIHI >= GETDATE() AND
			P.PROMOSYONTIPI = 'P7' AND 
			P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
			(
				P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
				ISNULL(P.CARIGRUP,'') = ''
			) AND
			P.REYONADI <> '' AND 
			VPLUNO = 0 AND 
			H.TUTAR >= ARATOPLAM AND
			ISKADEMELI = 1
		OPEN CURREYON
		
		FETCH NEXT FROM CURREYON
		INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE FROM #STABLE	
			
			DECLARE CURRSTOK CURSOR FAST_FORWARD FOR
			SELECT D.PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) / SUM(MIKTAR) AS FIYAT
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
			WHERE S.REYONADI = @REYONADI 
			GROUP BY D.PLUNO
			HAVING (SUM(MIKTAR) <> 0) AND (SUM(MIKTAR) - FLOOR(SUM(MIKTAR)) = 0)
			OPEN CURRSTOK
			
			FETCH NEXT FROM CURRSTOK
			INTO @STOKPLUNO, @STOKMIKTAR, @STOKFIYAT
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ADET = @STOKMIKTAR
				
				WHILE @ADET > 0 
				BEGIN
					INSERT INTO #STABLE(PLUNO, FIYAT, INDTUTAR, SIRANO)
					SELECT @STOKPLUNO, @STOKFIYAT, CASE WHEN @REYONINDYUZDE = 0 THEN @REYONINDTUTAR ELSE ROUND((@STOKFIYAT * @REYONINDYUZDE) / 100.00,2) END, 0
					
					SET @ADET = @ADET - 1
				END
			
				FETCH NEXT FROM CURRSTOK
				INTO @STOKPLUNO, @STOKMIKTAR, @STOKFIYAT
			END
			
			CLOSE CURRSTOK
			DEALLOCATE CURRSTOK
			
			UPDATE #STABLE
			SET SIRANO = H.SIRANO
			FROM #STABLE S
				INNER JOIN (SELECT ID, ROW_NUMBER() OVER(ORDER BY FIYAT DESC) AS SIRANO FROM #STABLE) AS H ON H.ID = S.ID
			
			DELETE FROM #STABLE 
			WHERE SIRANO % 2 <> 0

			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
			SELECT 
				'30',
				@REYONINDYUZDE,
				ROUND(INDTUTAR,2),
				SUBSTRING(M.STOKADI,1,20)+' KADEMELİ '+CONVERT(VARCHAR, CAST(INDTUTAR AS MONEY), 1)+' TL İND.',
				0,
				M.PLUNO
			FROM #STABLE S
				INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS M ON M.PLUNO = S.PLUNO
			WHERE INDTUTAR <> 0
			ORDER BY INDTUTAR DESC
			
			FETCH NEXT FROM CURREYON
			INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		END
		
		CLOSE CURREYON
		DEALLOCATE CURREYON		
		
		DROP TABLE #STABLE
	END
	
	DECLARE @TOPLAMINDIRIM FLOAT
	
	SELECT @TOPLAMINDIRIM  = SUM(INDTUTAR) FROM #RETTABLE
	
	SET @ARATOPLAM = @ARATOPLAM - ABS(ISNULL(@TOPLAMINDIRIM,0))
	
	IF @ARATOPLAM > 0
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			'27',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
				END
			END,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, 
						CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
							CASE 
								WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
								ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
							END
						END				
				)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			(
				CARIGRUP = @CARIGRUP OR
				CARIGRUP = ''
			) AND
			(
				PUAN > 0 OR
				ISNULL(PUANYUZDE,0) > 0
			) AND
			INDYUZDE = 0 AND
			INDTUTAR = 0
		ORDER BY ARATOPLAM DESC
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '27')
			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
			SELECT  
				TOP 1
				'27',
				INDYUZDE,
				ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
				CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
					CASE 
						WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
						ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
					END
				END,
				CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
				CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
					CONVERT(VARCHAR, 
						CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
							CASE 
								WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
								ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
							END
						END)+' PUAN'
				ELSE
					CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
				END
			FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			WHERE 
				ARATOPLAM <= @ARATOPLAM AND 
				BASLANGICTARIHI <= GETDATE() AND
				BITISTARIHI >= GETDATE() AND
				PROMOSYONTIPI = 'P1' AND 
				CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
				CARIGRUP = '' AND
				(
					PUAN > 0 OR
					ISNULL(PUANYUZDE,0) > 0
				) AND
				INDYUZDE = 0 AND
				INDTUTAR = 0
			ORDER BY ARATOPLAM DESC
	END

	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

ALTER PROCEDURE [dbo].[SP_PROMOSYON_URUN_IBM_KONTROL] 
	@CARITIPI		VARCHAR(1),
	@PLUNO			INT,
	@MIKTAR			FLOAT,
	@TUTAR			FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 

	DECLARE @STOKKODU VARCHAR(20)

	SELECT @STOKKODU = STOKKODU FROM TBL_STOK_MAIN WITH (NOLOCK)
	WHERE 
		PLUNO = @PLUNO AND
		ISNULL(ISINDIRIM,1) = 1
	
	SET @STOKKODU = ISNULL(@STOKKODU,'-987654')

	DECLARE @CARIGRUP VARCHAR(20)

	IF ISNULL(@CARIKODU,'') <> ''
		SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
		WHERE CARIKODU = @CARIKODU

	SET @CARIGRUP = ISNULL(@CARIGRUP,'')

	IF @CARITIPI = 'M' SET @CARITIPI = NULL
	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(@MIKTAR * PUAN),
		SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
	WHERE 
		U.STOKKODU = @STOKKODU AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		VREYONADI = '' AND
		CARIGRUP = @CARIGRUP AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) <= 1
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('03','05'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(@MIKTAR * PUAN),
			SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (SELECT STOKKODU, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1) GROUP BY STOKKODU, STOKADI) AS S ON S.STOKKODU = U.STOKKODU
		WHERE 
			U.STOKKODU = @STOKKODU AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			VREYONADI = '' AND
			CARIGRUP = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) <= 1
	
	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO


ALTER PROCEDURE [dbo].[SP_PROMOSYON_URUN_KONTROL] 
	@CARITIPI		VARCHAR(1),
	@PLUNO			INT,
	@MIKTAR			FLOAT,
	@TUTAR			FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 

	DECLARE @CARIGRUP VARCHAR(20)

	IF ISNULL(@CARIKODU,'') <> ''
		SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
		WHERE CARIKODU = @CARIKODU

	SET @CARIGRUP = ISNULL(@CARIGRUP,'')

	IF @CARITIPI = 'M' SET @CARITIPI = NULL
	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS)
	
	IF @CARIGRUP = 'NOBONUS' 
	BEGIN
		SELECT * FROM #RETTABLE
	
		DROP TABLE #RETTABLE
		
		RETURN
	END
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(@MIKTAR * PUAN),
		SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
	WHERE 
		U.PLUNO = @PLUNO AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		VREYONADI = '' AND
		CARIGRUP = @CARIGRUP AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) <= 1
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('03','01'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(@MIKTAR * PUAN),
			SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
		WHERE 
			U.PLUNO = @PLUNO AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			VREYONADI = '' AND
			CARIGRUP = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) <= 1
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('03','01'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT 
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '03' ELSE '01' END AS INDIRIMTIPI,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(@MIKTAR * PUAN),
			SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN @MIKTAR * INDTUTAR ELSE (@TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' TL İNDİRİM '+CASE WHEN PUAN > 0 THEN ' + '+CONVERT(VARCHAR, FLOOR(@MIKTAR * PUAN))+' PUAN' ELSE '' END
		FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
			INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI, REYONADI) AS S ON P.REYONADI = S.REYONADI
		WHERE 
			S.PLUNO = @PLUNO AND
			P.BASLANGICTARIHI <= GETDATE() AND
			P.BITISTARIHI >= GETDATE() AND
			P.PROMOSYONTIPI = 'R5' AND 
			P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
			(
				P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
				ISNULL(P.CARIGRUP,'') = ''
			) 


	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R1]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	CREATE TABLE #REYONPROMOSYON(REYONADI VARCHAR(20), AMIKTAR DECIMAL(21,6), VMIKTAR DECIMAL(21,6), INDYUZDE FLOAT, INDTUTAR FLOAT)
	
	INSERT INTO #REYONPROMOSYON(REYONADI, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
	SELECT 
		REYONADI,
		AMIKTAR, 
		VMIKTAR,
		INDYUZDE,
		INDTUTAR
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R1' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 
	
	IF EXISTS(SELECT TOP 1 * FROM #REYONPROMOSYON)
	BEGIN
		CREATE TABLE #INDIRIM(AREYONADI VARCHAR(20), INDIRIMTUTARI FLOAT, AMIKTAR FLOAT, VMIKTAR FLOAT)

		CREATE TABLE #FIS(
							ID INT IDENTITY(1,1) PRIMARY KEY, 
							REYONADI VARCHAR(20), 
							ASATISFIYAT FLOAT, 
							ASATISMIKTAR FLOAT, 
							ASATISTUTAR FLOAT, 
							AMIKTAR FLOAT, 
							VMIKTAR FLOAT, 
							INDYUZDE FLOAT, 
							INDTUTAR FLOAT
						)
		
		DECLARE
			@ID					INT, 
			@AREYONADI			VARCHAR(20),

			@ASATISFIYAT		FLOAT, 
			@ASATISMIKTAR		FLOAT, 
			@ASATISTUTAR		FLOAT, 

			@ALINACAKMIKTAR		FLOAT, 
			@VERILECEKMIKTAR	FLOAT, 
			@AKALANMIKTAR		FLOAT,
			@R1INDYUZDE			FLOAT,
			@R1INDTUTAR			FLOAT


		INSERT INTO #FIS(REYONADI, ASATISFIYAT, ASATISMIKTAR, ASATISTUTAR,  AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
		SELECT 
			S.REYONADI,
			D.FIYAT,
			SUM(D.MIKTAR) AS MIKTAR,
			SUM(D.TUTAR) AS TUTAR,
			P.AMIKTAR,
			P.VMIKTAR,
			P.INDYUZDE,
			P.INDTUTAR
		FROM TBL_BEKLETME_DETAY D
			INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
			INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI, REYONADI) S ON S.PLUNO = D.PLUNO
			INNER JOIN #REYONPROMOSYON P ON P.REYONADI COLLATE TURKISH_CI_AS = S.REYONADI 
		WHERE ISBEKLETME = 0
		GROUP BY S.REYONADI, D.FIYAT, P.AMIKTAR, P.VMIKTAR, P.INDYUZDE, P.INDTUTAR
		HAVING SUM(D.MIKTAR) > 0
		ORDER BY FIYAT DESC
		
		SET @AKALANMIKTAR = 0

		DECLARE CURR CURSOR FAST_FORWARD FOR
		SELECT 
			ID,
			REYONADI,
			ASATISFIYAT,
			ASATISMIKTAR,
			ASATISTUTAR,
			AMIKTAR,
			VMIKTAR,
			CASE WHEN INDYUZDE <= 0 THEN 100 ELSE INDYUZDE END,
			INDTUTAR
		FROM #FIS
		ORDER BY ASATISFIYAT DESC
		OPEN CURR

		FETCH NEXT FROM CURR
		INTO 
			@ID					,
			@AREYONADI			,
			@ASATISFIYAT		,
			@ASATISMIKTAR		,
			@ASATISTUTAR		,
			@ALINACAKMIKTAR		,
			@VERILECEKMIKTAR	,
			@R1INDYUZDE,
			@R1INDTUTAR

		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @AKALANMIKTAR = @AKALANMIKTAR + @ASATISMIKTAR

			WHILE @AKALANMIKTAR >= @ALINACAKMIKTAR 
			BEGIN
				INSERT INTO #INDIRIM(AREYONADI, INDIRIMTUTARI, AMIKTAR, VMIKTAR)
				SELECT @AREYONADI, CASE WHEN @R1INDTUTAR > 0 THEN @R1INDTUTAR ELSE ROUND(((@VERILECEKMIKTAR * @ASATISFIYAT) * @R1INDYUZDE / 100.00),2) END , @ALINACAKMIKTAR, @VERILECEKMIKTAR

				SET @AKALANMIKTAR = @AKALANMIKTAR - @ALINACAKMIKTAR
			END
	
			FETCH NEXT FROM CURR
			INTO 
				@ID					,
				@AREYONADI			,
				@ASATISFIYAT		,
				@ASATISMIKTAR		,
				@ASATISTUTAR		,
				@ALINACAKMIKTAR		,
				@VERILECEKMIKTAR	,
				@R1INDYUZDE,
				@R1INDTUTAR

		END

		CLOSE CURR
		DEALLOCATE CURR

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT 
			'25',
			0,
			SUM(INDIRIMTUTARI) AS INDIRIMTUTARI,
			SUBSTRING(AREYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, SUM(AMIKTAR))+' ADET ALANA '+CONVERT(VARCHAR, SUM(VMIKTAR))+' ADET ÜRÜNDE '+CONVERT(VARCHAR, CAST(ROUND(SUM(INDIRIMTUTARI),2) AS MONEY),1)+' TL İNDİRİM',
			0
		FROM #INDIRIM
		GROUP BY AREYONADI

		DROP TABLE #FIS
		DROP TABLE #INDIRIM		
	END
	
	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #REYONPROMOSYON
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R2]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		CASE WHEN P.INDTUTAR > 0 THEN P.INDTUTAR ELSE ROUND((T.TUTAR * INDYUZDE) / 100.00,2) END,
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN '+  CONVERT(VARCHAR, CAST(ROUND(P.ARATOPLAM,2) AS MONEY),1)+' TL ALANA '+P.VREYONADI+' RYN.DAN '+T.STOKADI+' ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN P.INDTUTAR > 0 THEN P.INDTUTAR ELSE ROUND((T.TUTAR * INDYUZDE) / 100.00,2) END,2) AS MONEY),1)+' TL İND.',
		0,
		T.PLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.PLUNO, S.STOKADI, S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.PLUNO, S.STOKADI, S.REYONADI
						HAVING SUM(D.MIKTAR) > 0
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.PLUNO, S.STOKADI, S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.PLUNO, S.STOKADI, S.REYONADI
						HAVING SUM(D.MIKTAR) > 0
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.VREYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R2' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		H.TUTAR >= ARATOPLAM 

	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R3]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON
	CREATE TABLE #REYONPROMOSYON(REYONADI VARCHAR(20), VREYONADI VARCHAR(20), AMIKTAR DECIMAL(21,6), VMIKTAR DECIMAL(21,6), INDYUZDE FLOAT, INDTUTAR FLOAT)

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)
	
	INSERT INTO #REYONPROMOSYON(REYONADI, VREYONADI, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
	SELECT 
		REYONADI,
		VREYONADI,
		AMIKTAR, 
		VMIKTAR,
		INDYUZDE,
		INDTUTAR
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R3' AND
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 

SELECT R.REYONADI, R.VREYONADI, FLOOR(SUM(D.MIKTAR) / R.AMIKTAR) * R.VMIKTAR AS VERILMESIGEREKENMIKTAR, R.AMIKTAR, R.VMIKTAR, R.INDYUZDE, R.INDTUTAR
INTO #ALINANTBL FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
	INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	INNER JOIN #REYONPROMOSYON R WITH (NOLOCK) ON R.REYONADI = S.REYONADI
GROUP BY R.REYONADI, R.VREYONADI, R.AMIKTAR, R.VMIKTAR, R.INDYUZDE, R.INDTUTAR
HAVING SUM(D.MIKTAR) >= R.AMIKTAR

DECLARE @REYONADI VARCHAR(20), @VREYONADI VARCHAR(20), @VERILMESIGEREKENMIKTAR FLOAT, @AMIKTAR FLOAT, @VMIKTAR FLOAT, @KALANMIKTAR FLOAT, @INDYUZDE FLOAT, @INDTUTAR FLOAT
DECLARE @PLUNO INT, @STOKADI VARCHAR(255), @FIYAT FLOAT, @MIKTAR FLOAT, @INDIRIMTUTARI FLOAT

DECLARE CURR CURSOR FAST_FORWARD FOR
SELECT REYONADI, VREYONADI, VERILMESIGEREKENMIKTAR, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR FROM #ALINANTBL
OPEN CURR

FETCH NEXT FROM CURR
INTO @REYONADI, @VREYONADI, @VERILMESIGEREKENMIKTAR, @AMIKTAR, @VMIKTAR, @INDYUZDE, @INDTUTAR

WHILE @@FETCH_STATUS = 0
BEGIN
	SET @KALANMIKTAR = @VERILMESIGEREKENMIKTAR
	
	DECLARE CURRV CURSOR FAST_FORWARD FOR
	SELECT D.PLUNO, S.STOKADI, D.FIYAT, SUM(D.MIKTAR) AS MIKTAR
	FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
		INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	WHERE S.REYONADI = @VREYONADI
	GROUP BY D.PLUNO, S.STOKADI, D.FIYAT
	HAVING SUM(D.MIKTAR) > 0
	ORDER BY D.FIYAT ASC
	OPEN CURRV

	FETCH NEXT FROM CURRV
	INTO @PLUNO, @STOKADI, @FIYAT, @MIKTAR

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE @PROMOSYONMIKTARI FLOAT
		SET @PROMOSYONMIKTARI = 0

		IF @KALANMIKTAR > 0
		BEGIN
			IF @KALANMIKTAR >=  @MIKTAR
				SET @PROMOSYONMIKTARI = @MIKTAR
			ELSE 
				SET @PROMOSYONMIKTARI = @KALANMIKTAR
		
			SET @KALANMIKTAR = @KALANMIKTAR - @MIKTAR

			IF @INDTUTAR > 0
				SET @INDIRIMTUTARI = @INDTUTAR
			ELSE
				SET @INDIRIMTUTARI = ROUND((@PROMOSYONMIKTARI * @FIYAT) * CASE WHEN @INDYUZDE = 0 THEN 100.00 ELSE @INDYUZDE END / 100.00,2)

			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
			SELECT 
				'25',
				0,
				@INDIRIMTUTARI AS INDIRIMTUTARI,
				SUBSTRING(@REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, SUM(@AMIKTAR))+' ADET ALANA '+ @VREYONADI+' REYONUNDAN '+ CONVERT(VARCHAR, SUM(@VMIKTAR))+' ADET ÜRÜNDE '+CONVERT(VARCHAR, CAST(@INDIRIMTUTARI AS MONEY),1)+' TL İNDİRİM',
				0,
				@PLUNO
		END

		IF @KALANMIKTAR <= 0 BREAK
		FETCH NEXT FROM CURRV
		INTO @PLUNO, @STOKADI, @FIYAT, @MIKTAR
	END
	
	CLOSE CURRV
	DEALLOCATE CURRV


	
	FETCH NEXT FROM CURR
	INTO @REYONADI, @VREYONADI, @VERILMESIGEREKENMIKTAR, @AMIKTAR, @VMIKTAR, @INDYUZDE, @INDTUTAR
END

CLOSE CURR
DEALLOCATE CURR

SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE

DROP TABLE #ALINANTBL
DROP TABLE #REYONPROMOSYON
DROP TABLE #RETTABLE

GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R4]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		0,
		CASE 
			WHEN P.INDTUTAR > 0 THEN P.INDTUTAR
			ELSE (H.FIYAT * CASE WHEN P.INDYUZDE = 0 THEN 100.00 ELSE P.INDYUZDE END) / 100.00
		END,	
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN EN UCUZ ÜRÜNE '+
		CONVERT(VARCHAR, CAST( 
								CASE 
									WHEN P.INDTUTAR > 0 THEN P.INDTUTAR
									ELSE (H.FIYAT * CASE WHEN P.INDYUZDE = 0 THEN 100.00 ELSE P.INDYUZDE END) / 100.00
								END		
							AS MONEY), 1)+' TL İND.',
		0,
		(
			SELECT TOP 1 D.PLUNO FROM TBL_BEKLETME_DETAY D WITH (NOLOCK) 
				INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)   GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
			WHERE FISID = H.FISID AND S.REYONADI = H.REYONADI AND FIYAT = H.FIYAT
		) AS PLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT D.FISID, S.REYONADI, SUM(D.TUTAR) AS TUTAR, MIN(FIYAT) AS FIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY D.FISID, S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R4' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
	 	H.TUTAR >= P.ARATOPLAM  

	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R6]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL,
	@ARATOPLAM		FLOAT
AS
SET NOCOUNT ON
	CREATE TABLE #REYONPROMOSYON(ID INT IDENTITY(1,1) PRIMARY KEY, ARATOPLAM FLOAT, REYONADI VARCHAR(20), VREYONADI VARCHAR(20), VMIKTAR FLOAT, INDYUZDE FLOAT, INDTUTAR FLOAT, ISOK BIT, ALIMKATSAYI INT)

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)
	
	INSERT INTO #REYONPROMOSYON(ARATOPLAM, REYONADI, VREYONADI, VMIKTAR, INDYUZDE, INDTUTAR, ISOK)
	SELECT 
		ARATOPLAM,
		REYONADI,
		VREYONADI,
		VMIKTAR,
		INDYUZDE,
		INDTUTAR,
		0
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R6' AND
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 

SELECT MAX(R.ID) AS ID, FLOOR(SUM(D.TUTAR) / R.ARATOPLAM) AS ALIMKATSAYI
INTO #ALINANTBL FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
	INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	INNER JOIN #REYONPROMOSYON R WITH (NOLOCK) ON R.REYONADI = S.REYONADI
GROUP BY R.REYONADI, R.VREYONADI, R.ARATOPLAM
HAVING SUM(D.TUTAR) >= R.ARATOPLAM

UPDATE #REYONPROMOSYON
SET ISOK = 1,
	ALIMKATSAYI = A.ALIMKATSAYI
FROM #REYONPROMOSYON R
	INNER JOIN #ALINANTBL A ON A.ID = R.ID

DELETE FROM #REYONPROMOSYON
WHERE ISOK = 0

UPDATE #REYONPROMOSYON
SET ISOK = 0

SELECT 
	R.ARATOPLAM, 
	R.REYONADI, 
	R.VREYONADI, 
	R.VMIKTAR, 
	CASE 
		WHEN R.INDTUTAR > 0 THEN CASE WHEN FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) > ALIMKATSAYI THEN ALIMKATSAYI ELSE FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) END * R.INDTUTAR
	ELSE ((CASE WHEN FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) > ALIMKATSAYI THEN ALIMKATSAYI ELSE FLOOR(SUM(D.MIKTAR) / R.VMIKTAR) END  * AVG(D.FIYAT)) * R.INDYUZDE) / 100.00 
	END AS INDTUTAR
INTO #VERILENTBL FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
	INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
	INNER JOIN #REYONPROMOSYON R WITH (NOLOCK) ON R.VREYONADI = S.REYONADI
GROUP BY R.ARATOPLAM, R.REYONADI, R.VREYONADI, R.VMIKTAR, R.INDTUTAR, R.INDYUZDE, ALIMKATSAYI
HAVING SUM(D.MIKTAR) >= R.VMIKTAR




INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
SELECT 
	'25',
	0,
	INDTUTAR,
	SUBSTRING(REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(ROUND(ARATOPLAM,2) AS MONEY),1)+' TL ALIM VE '+ 
	SUBSTRING(VREYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, VMIKTAR)+' ADET VE ÜSTÜ ALIMA '+
	CONVERT(VARCHAR, CAST(INDTUTAR AS MONEY),1)+' TL İNDİRİM',
	0,
	NULL
FROM #VERILENTBL

SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE

DROP TABLE #ALINANTBL
DROP TABLE #VERILENTBL
DROP TABLE #REYONPROMOSYON
DROP TABLE #RETTABLE
GO


ALTER PROCEDURE [dbo].[PR_FIS_MAIN]
	@ID	INT = NULL,
	@GONDERENVKN VARCHAR(20) = NULL
AS
	SET @GONDERENVKN = ISNULL(@GONDERENVKN, '11111111111')

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

	DECLARE 
		@DETAYID INT, @PLUNO INT, @TIP VARCHAR(3), @MIKTAR FLOAT, @TUTAR FLOAT,
		@IPTPLUNO INT, @IPTMIKTAR FLOAT, @IPTTUTAR FLOAT, @ARATOPLAMIND FLOAT, @ARATOPLAMART FLOAT, @INDORAN FLOAT, @ARTORAN FLOAT

	SELECT 
		@ARATOPLAMIND = ABS(INDTUTAR),
		@ARATOPLAMART = ARTTUTAR 
	FROM TBL_FIS_MAIN
	WHERE ID = @ID

	SELECT * INTO #DETAY 
	FROM TBL_FIS_DETAY
	WHERE FISID = @ID
	ORDER BY ID DESC

	DECLARE CURRD CURSOR FAST_FORWARD FOR
	SELECT ID, PLUNO, TIP, ABS(MIKTAR), ABS(TUTAR) FROM #DETAY 
	ORDER BY ID DESC
	OPEN CURRD

	FETCH NEXT FROM CURRD
	INTO @DETAYID, @PLUNO, @TIP, @MIKTAR, @TUTAR 

	SET @IPTPLUNO = 0

	WHILE @@FETCH_STATUS = 0  
	BEGIN
		IF @TIP = 'IPT'
		BEGIN
			SET @IPTPLUNO = @PLUNO		
			SET @IPTMIKTAR = @MIKTAR
			SET @IPTTUTAR = @TUTAR
		END		
		ELSE IF (@IPTPLUNO > 0) AND (@IPTPLUNO = @PLUNO)
		BEGIN
			UPDATE #DETAY
			SET MIKTAR = MIKTAR - @IPTMIKTAR, 
				TUTAR = TUTAR - @IPTTUTAR
			WHERE ID = @DETAYID
			
			SET @IPTPLUNO = 0
		END
		
		FETCH NEXT FROM CURRD
		INTO @DETAYID, @PLUNO, @TIP, @MIKTAR, @TUTAR 
	END

	CLOSE CURRD
	DEALLOCATE CURRD

	SELECT 
		@INDORAN = CASE WHEN SUM(TUTAR) -  SUM(ABS(INDTUTAR)) - SUM(ARTTUTAR) = 0 THEN 0 ELSE @ARATOPLAMIND / (SUM(TUTAR) -  SUM(ABS(INDTUTAR)) + SUM(ARTTUTAR)) END,
		@ARTORAN = CASE WHEN SUM(TUTAR) -  SUM(ABS(INDTUTAR)) - SUM(ARTTUTAR) = 0 THEN 0 ELSE @ARATOPLAMART / (SUM(TUTAR) -  SUM(ABS(INDTUTAR)) + SUM(ARTTUTAR)) END
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0

	UPDATE #DETAY
	SET INDTUTAR = -1 * ((ABS(INDTUTAR) + (@INDORAN * (TUTAR - ABS(INDTUTAR) + ARTTUTAR)))),
		ARTTUTAR = ((ABS(ARTTUTAR) + (@ARTORAN * (TUTAR - ABS(INDTUTAR) + ARTTUTAR)))),
		INDYUZDE = 0,
		ARTYUZDE = 0 
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0

	SELECT 
			@ARATOPLAMIND = SUM(INDTUTAR), 
			@ARATOPLAMART = SUM(ARTTUTAR)
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0


	DECLARE 
		@GRAMAJLIBARKODLAR VARCHAR(MAX)
	
	SET @GRAMAJLIBARKODLAR = NULL
	
	SELECT
		@GRAMAJLIBARKODLAR = 
						COALESCE(
								@GRAMAJLIBARKODLAR + CHAR(13)+dbo.CHECKSUMKONTROL(D.BARKOD+dbo.ZL(ROUND(MIKTAR*1000,0),5),13),
								dbo.CHECKSUMKONTROL(D.BARKOD+dbo.ZL(ROUND(MIKTAR*1000,0),5),13)
								)	
	FROM #DETAY D
			INNER JOIN TBL_STOK_MAIN M WITH (NOLOCK) ON M.BARKOD = D.BARKOD
	WHERE M.TARTILI = 'E'
	

	DECLARE 
		@TUMBARKODLAR VARCHAR(MAX)
	
	SET @TUMBARKODLAR = NULL
	
	SELECT
		@TUMBARKODLAR = 
						COALESCE(
								@TUMBARKODLAR + '"'+D.BARKOD+'*'+dbo.ZL(SUM(MIKTAR),10),
								D.BARKOD+'*'+dbo.ZL(SUM(MIKTAR),10)
								)	
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE FISID = @ID
	GROUP BY D.BARKOD
	HAVING SUM(MIKTAR) > 0
	ORDER BY MIN(D.ID)

	DROP TABLE #DETAY
	

	DECLARE
		@ARATOPIND FLOAT,
		@FISTUTAR FLOAT

	SELECT @FISTUTAR = TUTAR + ABS(INDTUTAR) - ARTTUTAR, @ARATOPIND = ABS(INDTUTAR) FROM TBL_FIS_MAIN WHERE ID = @ID

	SELECT KDV, SUM((TUTAR - ABS(INDTUTAR) + ARTTUTAR)) AS TUTAR
	INTO #KDVTBL FROM TBL_FIS_DETAY WITH (NOLOCK)
	WHERE FISID = @ID AND (TIP IN ('SAT', 'IPT'))
	GROUP BY KDV

	DELETE FROM #KDVTBL WHERE TUTAR = 0

	SELECT KDV, TUTAR - CASE WHEN @FISTUTAR = 0 THEN 0 ELSE ((TUTAR / @FISTUTAR) * @ARATOPIND) END  AS NETTUTAR INTO #RETTABLE
	FROM #KDVTBL

	DECLARE @KDVHARICTOPLAM FLOAT

	SELECT
		@ID AS FISID,
		KDV,
		ROUND(SUM((NETTUTAR / (1 + (KDV / 100.00)))),2) AS KDVMATRAHI,
		ROUND(SUM((NETTUTAR - (NETTUTAR / (1 + (KDV / 100.00))))),2) AS KDVTUTARI,
		ROUND(SUM(NETTUTAR),2) AS TUTAR
	INTO #KDVTOP FROM #RETTABLE WITH (NOLOCK)
	GROUP BY KDV
	
	SELECT @KDVHARICTOPLAM = SUM(KDVMATRAHI) FROM #KDVTOP
	
	SET @KDVHARICTOPLAM = ISNULL(@KDVHARICTOPLAM,0)

	DECLARE @KDVJSON VARCHAR(MAX)
	SELECT 
	  @KDVJSON = STUFF((
		SELECT 
			', "kdvmatrah('+CONVERT(VARCHAR, KDV)+')":"' + CONVERT(VARCHAR, KDVMATRAHI) +'"'+
			', "hesaplanankdv('+CONVERT(VARCHAR, KDV)+')":"' + CONVERT(VARCHAR, KDVTUTARI) +'"'
		FROM #KDVTOP 
		WHERE (FISID = Results.FISID) 
		FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
	  ,1,2,'') 
	FROM #KDVTOP Results
	GROUP BY FISID
	
	SELECT 
		F.*, 
		CONVERT(VARCHAR, F.TARIH, 112)+SUBSTRING(REPLACE(CONVERT(VARCHAR, F.TARIH, 114),':',''),1,6)+dbo.ZL(KASANO,3) AS FISBARKOD,
		ISNULL(ABS(@ARATOPLAMIND), 0) AS TOPLAMINDTUTARI, ISNULL(@ARATOPLAMART, 0) AS TOPLAMARTTUTARI,
		C.VERGIDAIRESI,
		C.ADRES ,
		C.TELEFON,
		ABS(ISNULL((SELECT SUM(INDTUTAR) FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE FISID = F.ID AND PROMOSYONTIPI = 0),0)) AS TICKETTUTAR,
		ISNULL((SELECT COUNT(*) FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE FISID = F.ID AND ISTICKET = 1),0) AS ISTICKET,
		ISNULL(
				(SELECT SUM(D.TUTAR) FROM TBL_FIS_DETAY D WITH (NOLOCK) 
					INNER JOIN TBL_STOK_MAIN M ON M.BARKOD = D.BARKOD
				WHERE D.FISID = F.ID AND M.REYONADI = 'CEK'
 				),0) AS INDIRIMREYONTUTARI,
		@GRAMAJLIBARKODLAR AS GRAMAJLIBARKOD,
		@TUMBARKODLAR AS TUMBARKODLAR,
		'{"vkntckn":"'+ISNULL(@GONDERENVKN,'')+
		'","avkntckn":"'+CASE WHEN ISNULL(F.VERGINO,'') = '' THEN '11111111111' ELSE F.VERGINO END+
		'","senaryo":"'+CASE WHEN F.ISEFATURA = 1 THEN 'TEMELFATURA' ELSE 'EARSIVFATURA' END +
		'","tip":"SATIS'+
		'","tarih":"'+REPLACE(CONVERT(VARCHAR, F.TARIH, 102),'.','-') +
		'","no":"'+EFATURAKODU+
		'","ettn":"'+UUID+
		'","parabirimi":"TRY'+
		'","malhizmettoplam":"'+CONVERT(VARCHAR, @KDVHARICTOPLAM)+
		'",'+@KDVJSON+ 
		',"vergidahil":"'+CONVERT(VARCHAR, F.TUTAR)+
		'","odenecek":"'+CONVERT(VARCHAR, F.TUTAR)+'"}' AS EFATURAQRKOD
	FROM TBL_FIS_MAIN F WITH (NOLOCK)
		LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		
	WHERE F.ID = @ID

	DROP TABLE #KDVTBL
	DROP TABLE #RETTABLE
	DROP TABLE #KDVTOP
GO
ALTER PROCEDURE [dbo].[PR_FIS_MAIN]
	@ID	INT = NULL,
	@GONDERENVKN VARCHAR(20) = NULL
AS
	SET @GONDERENVKN = ISNULL(@GONDERENVKN, '11111111111')

	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_FIS_MAIN WITH (NOLOCK)

	DECLARE 
		@DETAYID INT, @PLUNO INT, @TIP VARCHAR(3), @MIKTAR FLOAT, @TUTAR FLOAT,
		@IPTPLUNO INT, @IPTMIKTAR FLOAT, @IPTTUTAR FLOAT, @ARATOPLAMIND FLOAT, @ARATOPLAMART FLOAT, @INDORAN FLOAT, @ARTORAN FLOAT

	SELECT 
		@ARATOPLAMIND = ABS(INDTUTAR),
		@ARATOPLAMART = ARTTUTAR 
	FROM TBL_FIS_MAIN
	WHERE ID = @ID

	SELECT * INTO #DETAY 
	FROM TBL_FIS_DETAY
	WHERE FISID = @ID
	ORDER BY ID DESC

	DECLARE CURRD CURSOR FAST_FORWARD FOR
	SELECT ID, PLUNO, TIP, ABS(MIKTAR), ABS(TUTAR) FROM #DETAY 
	ORDER BY ID DESC
	OPEN CURRD

	FETCH NEXT FROM CURRD
	INTO @DETAYID, @PLUNO, @TIP, @MIKTAR, @TUTAR 

	SET @IPTPLUNO = 0

	WHILE @@FETCH_STATUS = 0  
	BEGIN
		IF @TIP = 'IPT'
		BEGIN
			SET @IPTPLUNO = @PLUNO		
			SET @IPTMIKTAR = @MIKTAR
			SET @IPTTUTAR = @TUTAR
		END		
		ELSE IF (@IPTPLUNO > 0) AND (@IPTPLUNO = @PLUNO)
		BEGIN
			UPDATE #DETAY
			SET MIKTAR = MIKTAR - @IPTMIKTAR, 
				TUTAR = TUTAR - @IPTTUTAR
			WHERE ID = @DETAYID
			
			SET @IPTPLUNO = 0
		END
		
		FETCH NEXT FROM CURRD
		INTO @DETAYID, @PLUNO, @TIP, @MIKTAR, @TUTAR 
	END

	CLOSE CURRD
	DEALLOCATE CURRD

	SELECT 
		@INDORAN = CASE WHEN SUM(TUTAR) -  SUM(ABS(INDTUTAR)) - SUM(ARTTUTAR) = 0 THEN 0 ELSE @ARATOPLAMIND / (SUM(TUTAR) -  SUM(ABS(INDTUTAR)) + SUM(ARTTUTAR)) END,
		@ARTORAN = CASE WHEN SUM(TUTAR) -  SUM(ABS(INDTUTAR)) - SUM(ARTTUTAR) = 0 THEN 0 ELSE @ARATOPLAMART / (SUM(TUTAR) -  SUM(ABS(INDTUTAR)) + SUM(ARTTUTAR)) END
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0

	UPDATE #DETAY
	SET INDTUTAR = -1 * ((ABS(INDTUTAR) + (@INDORAN * (TUTAR - ABS(INDTUTAR) + ARTTUTAR)))),
		ARTTUTAR = ((ABS(ARTTUTAR) + (@ARTORAN * (TUTAR - ABS(INDTUTAR) + ARTTUTAR)))),
		INDYUZDE = 0,
		ARTYUZDE = 0 
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0

	SELECT 
			@ARATOPLAMIND = SUM(INDTUTAR), 
			@ARATOPLAMART = SUM(ARTTUTAR)
	FROM #DETAY
	WHERE TIP = 'SAT' AND MIKTAR > 0


	DECLARE 
		@GRAMAJLIBARKODLAR VARCHAR(MAX)
	
	SET @GRAMAJLIBARKODLAR = NULL
	
	SELECT
		@GRAMAJLIBARKODLAR = 
						COALESCE(
								@GRAMAJLIBARKODLAR + CHAR(13)+dbo.CHECKSUMKONTROL(D.BARKOD+dbo.ZL(ROUND(MIKTAR*1000,0),5),13),
								dbo.CHECKSUMKONTROL(D.BARKOD+dbo.ZL(ROUND(MIKTAR*1000,0),5),13)
								)	
	FROM #DETAY D
			INNER JOIN TBL_STOK_MAIN M WITH (NOLOCK) ON M.BARKOD = D.BARKOD
	WHERE M.TARTILI = 'E'
	

	DECLARE 
		@TUMBARKODLAR VARCHAR(MAX)
	
	SET @TUMBARKODLAR = NULL
	
	SELECT
		@TUMBARKODLAR = 
						COALESCE(
								@TUMBARKODLAR + '"'+D.BARKOD+'*'+dbo.ZL(SUM(MIKTAR),10),
								D.BARKOD+'*'+dbo.ZL(SUM(MIKTAR),10)
								)	
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE FISID = @ID
	GROUP BY D.BARKOD
	HAVING SUM(MIKTAR) > 0
	ORDER BY MIN(D.ID)

	DROP TABLE #DETAY
	

	DECLARE
		@ARATOPIND FLOAT,
		@FISTUTAR FLOAT

	SELECT @FISTUTAR = TUTAR + ABS(INDTUTAR) - ARTTUTAR, @ARATOPIND = ABS(INDTUTAR) FROM TBL_FIS_MAIN WHERE ID = @ID

	SELECT KDV, SUM((TUTAR - ABS(INDTUTAR) + ARTTUTAR)) AS TUTAR
	INTO #KDVTBL FROM TBL_FIS_DETAY WITH (NOLOCK)
	WHERE FISID = @ID AND (TIP IN ('SAT', 'IPT'))
	GROUP BY KDV

	DELETE FROM #KDVTBL WHERE TUTAR = 0

	SELECT KDV, TUTAR - CASE WHEN @FISTUTAR = 0 THEN 0 ELSE ((TUTAR / @FISTUTAR) * @ARATOPIND) END  AS NETTUTAR INTO #RETTABLE
	FROM #KDVTBL

	DECLARE @KDVHARICTOPLAM FLOAT

	SELECT
		@ID AS FISID,
		KDV,
		ROUND(SUM((NETTUTAR / (1 + (KDV / 100.00)))),2) AS KDVMATRAHI,
		ROUND(SUM((NETTUTAR - (NETTUTAR / (1 + (KDV / 100.00))))),2) AS KDVTUTARI,
		ROUND(SUM(NETTUTAR),2) AS TUTAR
	INTO #KDVTOP FROM #RETTABLE WITH (NOLOCK)
	GROUP BY KDV
	
	SELECT @KDVHARICTOPLAM = SUM(KDVMATRAHI) FROM #KDVTOP
	
	SET @KDVHARICTOPLAM = ISNULL(@KDVHARICTOPLAM,0)

	DECLARE @KDVJSON VARCHAR(MAX)
	SELECT 
	  @KDVJSON = STUFF((
		SELECT 
			', "kdvmatrah('+CONVERT(VARCHAR, KDV)+')":"' + CONVERT(VARCHAR, KDVMATRAHI) +'"'+
			', "hesaplanankdv('+CONVERT(VARCHAR, KDV)+')":"' + CONVERT(VARCHAR, KDVTUTARI) +'"'
		FROM #KDVTOP 
		WHERE (FISID = Results.FISID) 
		FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
	  ,1,2,'') 
	FROM #KDVTOP Results
	GROUP BY FISID
	
	SELECT 
		F.*, 
		CONVERT(VARCHAR, F.TARIH, 112)+SUBSTRING(REPLACE(CONVERT(VARCHAR, F.TARIH, 114),':',''),1,6)+dbo.ZL(KASANO,3) AS FISBARKOD,
		ISNULL(ABS(@ARATOPLAMIND), 0) AS TOPLAMINDTUTARI, ISNULL(@ARATOPLAMART, 0) AS TOPLAMARTTUTARI,
		C.VERGIDAIRESI,
		C.ADRES ,
		C.TELEFON,
		ABS(ISNULL((SELECT SUM(INDTUTAR) FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE FISID = F.ID AND PROMOSYONTIPI = 0),0)) AS TICKETTUTAR,
		ISNULL((SELECT COUNT(*) FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE FISID = F.ID AND ISTICKET = 1),0) AS ISTICKET,
		ISNULL(
				(SELECT SUM(D.TUTAR) FROM TBL_FIS_DETAY D WITH (NOLOCK) 
					INNER JOIN TBL_STOK_MAIN M ON M.BARKOD = D.BARKOD
				WHERE D.FISID = F.ID AND M.REYONADI = 'CEK'
 				),0) AS INDIRIMREYONTUTARI,
		@GRAMAJLIBARKODLAR AS GRAMAJLIBARKOD,
		@TUMBARKODLAR AS TUMBARKODLAR,
		'{"vkntckn":"'+ISNULL(@GONDERENVKN,'')+
		'","avkntckn":"'+CASE WHEN ISNULL(F.VERGINO,'') = '' THEN '11111111111' ELSE F.VERGINO END+
		'","senaryo":"'+CASE WHEN F.ISEFATURA = 1 THEN 'TEMELFATURA' ELSE 'EARSIVFATURA' END +
		'","tip":"SATIS'+
		'","tarih":"'+REPLACE(CONVERT(VARCHAR, F.TARIH, 102),'.','-') +
		'","no":"'+EFATURAKODU+
		'","ettn":"'+UUID+
		'","parabirimi":"TRY'+
		'","malhizmettoplam":"'+CONVERT(VARCHAR, @KDVHARICTOPLAM)+
		'",'+@KDVJSON+ 
		',"vergidahil":"'+CONVERT(VARCHAR, F.TUTAR)+
		'","odenecek":"'+CONVERT(VARCHAR, F.TUTAR)+'"}' AS EFATURAQRKOD
	FROM TBL_FIS_MAIN F WITH (NOLOCK)
		LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		
	WHERE F.ID = @ID

	DROP TABLE #KDVTBL
	DROP TABLE #RETTABLE
	DROP TABLE #KDVTOP
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_POS_GUN_SONU_MAIN]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_POS_GUN_SONU_MAIN](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[SERIALNO] [varchar](50) NULL,
		[BATCHNO] [varchar](20) NULL,
		[TARIHSAAT] [datetime] NULL,
	 CONSTRAINT [PK_TBL_POS_GUN_SONU_MAIN] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
	CREATE UNIQUE NONCLUSTERED INDEX [IX_TBL_POS_GUN_SONU_MAIN] ON [dbo].[TBL_POS_GUN_SONU_MAIN]
	(
		[SERIALNO] ASC,
		[BATCHNO] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
END
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_POS_GUN_SONU_DETAY]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_POS_GUN_SONU_DETAY](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[GUNSONUID] [int] NOT NULL,
		[BANKAADI] [varchar](255) NOT NULL,
		[ISYERINO] [varchar](255) NOT NULL,
		[TERMINALNO] [varchar](255) NOT NULL,
	 CONSTRAINT [PK_TBL_POS_GUN_SONU_DETAY] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
	CREATE NONCLUSTERED INDEX [IX_TBL_POS_GUN_SONU_DETAY] ON [dbo].[TBL_POS_GUN_SONU_DETAY]
	(
		[GUNSONUID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	ALTER TABLE [dbo].[TBL_POS_GUN_SONU_DETAY]  WITH CHECK ADD  CONSTRAINT [FK_TBL_POS_GUN_SONU_DETAY_TBL_POS_GUN_SONU_MAIN] FOREIGN KEY([GUNSONUID])
	REFERENCES [dbo].[TBL_POS_GUN_SONU_MAIN] ([ID])

	ALTER TABLE [dbo].[TBL_POS_GUN_SONU_DETAY] CHECK CONSTRAINT [FK_TBL_POS_GUN_SONU_DETAY_TBL_POS_GUN_SONU_MAIN]
END
GO

IF  NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TBL_POS_GUN_SONU_ODEME_DETAY]') AND type in (N'U'))
BEGIN
	CREATE TABLE [dbo].[TBL_POS_GUN_SONU_ODEME_DETAY](
		[ID] [int] IDENTITY(1,1) NOT NULL,
		[DETAYID] [int] NOT NULL,
		[TITLE] [varchar](255) NOT NULL,
		[OPERATIONNAME] [varchar](50) NOT NULL,
		[TRANSACTIONCOUNT] [int] NOT NULL,
		[TOTALAMOUNT] [float] NOT NULL,
	 CONSTRAINT [PK_TBL_POS_GUN_SONU_ODEME_DETAY] PRIMARY KEY CLUSTERED 
	(
		[ID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
	CREATE NONCLUSTERED INDEX [IX_TBL_POS_GUN_SONU_ODEME_DETAY] ON [dbo].[TBL_POS_GUN_SONU_ODEME_DETAY]
	(
		[DETAYID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	ALTER TABLE [dbo].[TBL_POS_GUN_SONU_ODEME_DETAY]  WITH CHECK ADD  CONSTRAINT [FK_TBL_POS_GUN_SONU_ODEME_DETAY_TBL_POS_GUN_SONU_DETAY] FOREIGN KEY([DETAYID])
	REFERENCES [dbo].[TBL_POS_GUN_SONU_DETAY] ([ID])

	ALTER TABLE [dbo].[TBL_POS_GUN_SONU_ODEME_DETAY] CHECK CONSTRAINT [FK_TBL_POS_GUN_SONU_ODEME_DETAY_TBL_POS_GUN_SONU_DETAY]
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_POS_GUN_SONU_ODEME_DETAY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_POS_GUN_SONU_ODEME_DETAY]
GO
CREATE PROCEDURE [dbo].[PR_POS_GUN_SONU_ODEME_DETAY]
	@ID INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_POS_GUN_SONU_MAIN WITH (NOLOCK)

	SELECT * FROM TBL_POS_GUN_SONU_ODEME_DETAY WITH (NOLOCK)
	WHERE DETAYID IN (SELECT ID FROM TBL_POS_GUN_SONU_DETAY WITH (NOLOCK) WHERE GUNSONUID =  @ID)
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_POS_GUN_SONU_DETAY]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_POS_GUN_SONU_DETAY]
GO
CREATE PROCEDURE [dbo].[PR_POS_GUN_SONU_DETAY]
	@ID INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_POS_GUN_SONU_MAIN WITH (NOLOCK)

	SELECT * FROM TBL_POS_GUN_SONU_DETAY WITH (NOLOCK)
	WHERE GUNSONUID =  @ID
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PR_POS_GUN_SONU_MAIN]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[PR_POS_GUN_SONU_MAIN]
GO
CREATE PROCEDURE [dbo].[PR_POS_GUN_SONU_MAIN]
	@ID INT = NULL
AS
	IF @ID IS NULL
		SELECT @ID = MAX(ID) FROM TBL_POS_GUN_SONU_MAIN WITH (NOLOCK)

	SELECT * FROM TBL_POS_GUN_SONU_MAIN WITH (NOLOCK)
	WHERE ID =  @ID
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_GUN_SONU_ODEME_DETAY_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_GUN_SONU_ODEME_DETAY_INSERT]
GO
CREATE PROCEDURE [dbo].[SP_POS_GUN_SONU_ODEME_DETAY_INSERT]
	@DETAYID			INT,
	@TITLE				VARCHAR(255),
	@OPERATIONNAME		VARCHAR(50),
	@TRANSACTIONCOUNT	INT,		
	@TOTALAMOUNT		FLOAT	
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO TBL_POS_GUN_SONU_ODEME_DETAY(DETAYID, TITLE, OPERATIONNAME, TRANSACTIONCOUNT, TOTALAMOUNT)
	SELECT @DETAYID, @TITLE, @OPERATIONNAME, @TRANSACTIONCOUNT, @TOTALAMOUNT
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_GUN_SONU_DETAY_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_GUN_SONU_DETAY_INSERT]
GO
CREATE PROCEDURE [dbo].[SP_POS_GUN_SONU_DETAY_INSERT]
	@GUNSONUID	INT,
	@BANKAADI	VARCHAR(255),
	@ISYERINO	VARCHAR(255),
	@TERMINALNO	VARCHAR(255)
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO TBL_POS_GUN_SONU_DETAY(GUNSONUID, BANKAADI, ISYERINO, TERMINALNO)
	SELECT @GUNSONUID, @BANKAADI, @ISYERINO, @TERMINALNO
	
	RETURN ISNULL((SELECT MAX(ID) FROM TBL_POS_GUN_SONU_DETAY WITH (NOLOCK)),0)
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SP_POS_GUN_SONU_MAIN_INSERT]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[SP_POS_GUN_SONU_MAIN_INSERT]
GO
CREATE PROCEDURE [dbo].[SP_POS_GUN_SONU_MAIN_INSERT]
	@SERIALNO	VARCHAR(50),
	@BATCHNO	VARCHAR(20),
	@TARIHSAAT	DATETIME
AS
BEGIN
	SET NOCOUNT ON;
	INSERT INTO TBL_POS_GUN_SONU_MAIN(SERIALNO, BATCHNO, TARIHSAAT)
	SELECT @SERIALNO, @BATCHNO, @TARIHSAAT
	
	RETURN ISNULL((SELECT MAX(ID) FROM TBL_POS_GUN_SONU_MAIN WITH (NOLOCK)),0)
END
GO


IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_MAIN') AND name='OKCFISNO')
ALTER TABLE dbo.TBL_FIS_MAIN ADD
	OKCFISNO varchar(50) NULL
GO

ALTER PROCEDURE [dbo].[SP_FIS_MAIN_INSERT]
	@KASANO			INT,
	@BELGEKODU		VARCHAR(20),
	@TARIH			DATETIME,
	@TIP			TINYINT,
	@VERGINO		VARCHAR(20),
	@CARIKODU		VARCHAR(20),
	@CARIADI		VARCHAR(50),
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PARAUSTU		FLOAT,
	@ISEFATURA		BIT,
	@EFATURAKODU	VARCHAR(20),
	@UUID			VARCHAR(50),
	@ALIAS			VARCHAR(MAX),
	@PUAN			FLOAT,
	@ISSENDPUAN		BIT,
	@ACIKLAMA		VARCHAR(MAX) = NULL,
	@YETKILIKODU	VARCHAR(4) = NULL,
	@YETKILIADI		VARCHAR(20) = NULL,
	@OKCFISNO		VARCHAR(50) = NULL
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_MAIN(KASANO, BELGEKODU, TARIH, TIP, VERGINO, CARIKODU, CARIADI, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PARAUSTU, ISEFATURA, EFATURAKODU, UUID, ALIAS, PUAN, ISSENDPUAN, ACIKLAMA, YETKILIKODU, YETKILIADI, OKCFISNO)
	SELECT @KASANO, @BELGEKODU, @TARIH, @TIP, @VERGINO, @CARIKODU, @CARIADI, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PARAUSTU, @ISEFATURA, @EFATURAKODU, @UUID, @ALIAS, @PUAN, @ISSENDPUAN, @ACIKLAMA, @YETKILIKODU, @YETKILIADI, @OKCFISNO

	RETURN @@IDENTITY
GO


ALTER PROCEDURE [dbo].[SP_IMPORT_URUN_FILE]
	@ISDEGISEN BIT = 0,
	@ISTRUNCATETABLE BIT = 1
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)
CREATE TABLE #TEMPFILE(
						PLUNO INT, 
						BARKOD VARCHAR(20), 
						STOKADI VARCHAR(50), 
						FIYAT FLOAT, 
						DEPARTMAN INT,
						BIRIM VARCHAR(4),
						TARTILI VARCHAR(1),
						FIYAT2 FLOAT,
						FIYAT3 FLOAT,
						DOVIZKODU VARCHAR(10),
						ALISDEPARTMAN INT,
						STOKKODU VARCHAR(20),
						REYONADI VARCHAR(20),
						RENK VARCHAR(50),
						BEDEN VARCHAR(20),
						MODELKODU VARCHAR(20),
						TEVKIFATKODU VARCHAR(10),
						TEVKIFATACIKLAMA VARCHAR(100),
						TEVKIFATORANI INT,
						OTVKODU VARCHAR(10),
						OTVACIKLAMA VARCHAR(100),
						OTVORANI INT,
						ALISFIYAT FLOAT,
						ISINDIRIM BIT
					)
BEGIN TRY
	
--IF EXISTS(
--				SELECT TOP 1 1 FROM TBL_IMPORT_FILE 
--				WHERE PATINDEX('%[Ã‡]%', DATA COLLATE Latin1_General_bin) > 0
--			)
--	UPDATE TBL_IMPORT_FILE
--	SET DATA = dbo.utf8_to_utf16(DATA)

	DECLARE @DATA VARCHAR(MAX)

	SELECT TOP 1 @DATA = DATA FROM TBL_IMPORT_FILE
	
	IF LEN(@DATA) <= 82
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,20)) AS STOKADI,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,10),'.',''))/100 
			ELSE CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,9),'.',''))/100 END AS FIYAT,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(INT, SUBSTRING(DATA,58,2)) 
			ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS DEPARTMAN,
			CASE WHEN LEN(DATA) = 65 THEN 
				RTRIM(SUBSTRING(DATA,60,4)) 
			ELSE
				RTRIM(SUBSTRING(DATA,59,4)) END AS BIRIM,
			
			CASE WHEN LEN(DATA) = 65 THEN 
				SUBSTRING(DATA,64,1)
			ELSE
				SUBSTRING(DATA,63,1) END AS TARTILI,
			0 AS FIYAT2,
			0 AS FIYAT3,
			'TL' AS DOVIZKODU,
			CASE WHEN LEN(DATA) = 65 THEN CONVERT(INT, SUBSTRING(DATA,58,2)) ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,8,20)) AS STOKKODU,
			'' AS REYONADI,
			'' AS RENK,
			'' AS BEDEN,
			'' AS MODELKODU,
			'' AS TEVKIFATKODU,
			'' AS TEVKIFATACIKLAMA,
			0  AS TEVKIFATORANI,
			'' AS OTVKODU,
			'' AS OTVACIKLAMA,
			0  AS OTVORANI,
			0 AS ALISFIYAT,
			1 AS ISINDIRIM
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63 AND LEN(@DATA) = LEN(DATA)
	ELSE
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,50)) AS STOKADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,78,9),'.',''))/100 AS FIYAT,
			CONVERT(INT, SUBSTRING(DATA,87,2)) AS DEPARTMAN,
			RTRIM(SUBSTRING(DATA,89,4)) AS BIRIM,
			SUBSTRING(DATA,93,1) AS TARTILI,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,94,9),'.',''),'0')) / 100 AS FIYAT2,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,103,9),'.',''),'0')) / 100 AS FIYAT3,
			RTRIM(SUBSTRING(DATA,112,10)) AS DOVIZKODU,
			CONVERT(INT, SUBSTRING(DATA,122,2)) AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,124,20)) AS STOKKODU,
			RTRIM(SUBSTRING(DATA,144,20)) AS REYONADI,
			RTRIM(SUBSTRING(DATA,164,50)) AS RENK,
			RTRIM(SUBSTRING(DATA,214,20)) AS BEDEN,
			RTRIM(SUBSTRING(DATA,234,20)) AS MODELKODU,
			RTRIM(SUBSTRING(DATA,254,10)) AS TEVKIFATKODU,
			RTRIM(SUBSTRING(DATA,264,100)) AS TEVKIFATACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,364,3)) AS TEVKIFATORANI,
			RTRIM(SUBSTRING(DATA,367,10)) AS OTVKODU,
			RTRIM(SUBSTRING(DATA,377,100)) AS OTVACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,477,3)) AS OTVORANI,
			CONVERT(FLOAT, ISNULL(REPLACE(REPLACE(REPLACE(SUBSTRING(DATA,480,9),'.',''),CHAR(13),'0'),CHAR(10),'0'),'0'))/100 AS ALISFIYAT,
			CONVERT(BIT, CASE WHEN SUBSTRING(DATA,489,1) = '0' THEN 0 ELSE 1 END) AS ISINDIRIM
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63  AND LEN(@DATA) = LEN(DATA)
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : ÜRÜN DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

DELETE FROM #TEMPFILE
WHERE BARKOD IN (
                                                SELECT BARKOD FROM #TEMPFILE
                                                GROUP BY BARKOD
                                                HAVING COUNT(*) > 1
                                        )

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : URUN DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

DECLARE @DEPARTMAN INT

SELECT TOP 1 @DEPARTMAN = DEPARTMAN
FROM #TEMPFILE
WHERE DEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU DEPARTMAN TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

SET @DEPARTMAN = NULL

SELECT TOP 1 @DEPARTMAN = ALISDEPARTMAN
FROM #TEMPFILE
WHERE ALISDEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU ALIŞ DEPARTMANI TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE WHERE PLUNO = 0),0) > 1
BEGIN
	SET @ERRORMESSAGE = 'HATA : PLU NUMARASI SIFIR OLAN ÜRÜNLER MEVCUT.!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

CREATE TABLE #TMPREYON(PLUNO INT, REYONADI VARCHAR(20))

IF LEN(@DATA) <= 80
	INSERT INTO #TMPREYON(PLUNO, REYONADI)
	SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN WITH (NOLOCK)
	GROUP BY PLUNO, REYONADI

BEGIN TRAN

	IF @ISDEGISEN = 1
	BEGIN
		BEGIN TRY
			DELETE FROM TBL_STOK_MAIN
			WHERE PLUNO IN (SELECT PLUNO FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH

		BEGIN TRY
			DELETE FROM TBL_STOK_KOD
			WHERE BARKOD IN (SELECT BARKOD FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK KOD TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH
	END
	ELSE
	BEGIN
		IF ISNULL(@ISTRUNCATETABLE,1) = 1
		BEGIN
			TRUNCATE TABLE TBL_STOK_MAIN
			TRUNCATE TABLE TBL_STOK_KOD
		END
	END

	BEGIN TRY
		INSERT INTO TBL_STOK_MAIN(PLUNO, BARKOD, STOKADI, DEPARTMAN, KDV, BIRIM, FIYAT, FIYAT2, FIYAT3, TARTILI, CREATEDATE, CREATEUSERCODE, DOVIZKODU, ALISDEPARTMAN, ALISKDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT T.PLUNO, T.BARKOD, T.STOKADI, T.DEPARTMAN, D.KDV, T.BIRIM, T.FIYAT, CASE WHEN ISNULL(T.FIYAT2,0) = 0 THEN T.FIYAT ELSE T.FIYAT2 END, CASE WHEN ISNULL(T.FIYAT3,0) = 0 THEN T.FIYAT ELSE T.FIYAT3 END, T.TARTILI, GETDATE(), APP_NAME(), DOVIZKODU, T.ALISDEPARTMAN, A.KDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM FROM #TEMPFILE T
			INNER JOIN TBL_DEPARTMAN D WITH (NOLOCK) ON D.DEPARTMAN = T.DEPARTMAN
			INNER JOIN TBL_DEPARTMAN A WITH (NOLOCK) ON A.DEPARTMAN = T.ALISDEPARTMAN
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	BEGIN TRY
		SELECT BARKOD, STOKKODU, CONVERT(BIT,0) AS ISDELETE INTO #STOKKOD FROM #TEMPFILE
		GROUP BY BARKOD, STOKKODU

		UPDATE #STOKKOD
		SET ISDELETE = 1
		FROM #STOKKOD S
			INNER JOIN TBL_STOK_KOD K WITH (NOLOCK) ON K.BARKOD = S.BARKOD 

		INSERT INTO TBL_STOK_KOD(BARKOD, STOKKODU)
		SELECT BARKOD, STOKKODU FROM #STOKKOD
		WHERE ISDELETE = 0
		GROUP BY BARKOD, STOKKODU
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	IF LEN(@DATA) <= 80
		UPDATE TBL_STOK_MAIN 
		SET REYONADI = R.REYONADI
		FROM TBL_STOK_MAIN S
			INNER JOIN #TMPREYON R ON R.PLUNO = S.PLUNO	
	
	IF ISNULL((SELECT COUNT(*) FROM TBL_STOK_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END
	
DROP TABLE #TEMPFILE
DROP TABLE #TMPREYON

COMMIT TRAN
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



ALTER PROCEDURE [dbo].[SP_IMPORT_FILE]
	@FILENAME	NVARCHAR(500),
	@FILETYPE	INT,
	@ISTRUNCATETABLE BIT = 1
AS
	SET NOCOUNT ON
	SET @ISTRUNCATETABLE = ISNULL(@ISTRUNCATETABLE,1)
	DECLARE
		@DURUM		TINYINT,
		@ACIKLAMA	VARCHAR(MAX),
		@ISERROR	BIT	,
		@DOSYAADI	VARCHAR(MAX)

	TRUNCATE TABLE TBL_IMPORT_FILE

	BEGIN TRY
		DECLARE @sql NVARCHAR(4000) = 'BULK INSERT TBL_IMPORT_FILE FROM ''' + @FILENAME + ''' WITH (ROWTERMINATOR = ''0x0A'', CODEPAGE = ''1254'')';
		EXEC(@sql);
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN (BULK INSERT) HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		IF @FILETYPE = 107
			EXEC SP_IMPORT_URUN_FILE 0, @ISTRUNCATETABLE
		ELSE
		IF @FILETYPE = 1071
			EXEC SP_IMPORT_URUN_FILE 1
		ELSE
		IF @FILETYPE = 108
			EXEC SP_IMPORT_CARI_FILE 0
		ELSE
		IF @FILETYPE = 1081
			EXEC SP_IMPORT_CARI_FILE 1
		ELSE
		IF @FILETYPE = 109
			EXEC SP_IMPORT_KASIYER_FILE
		ELSE
		IF @FILETYPE = 110
			EXEC SP_IMPORT_DOVIZ_FILE
		ELSE
		IF @FILETYPE = 126
			EXEC SP_IMPORT_REYON_FILE
		ELSE
		IF @FILETYPE = 113
			EXEC SP_IMPORT_PROMOSYON_FILE
		ELSE
		IF @FILETYPE = 138
			EXEC SP_IMPORT_OZELKOD_FILE
		ELSE
		IF @FILETYPE = 907
			EXEC SP_IMPORT_URUN_IBM_FILE
		ELSE
		IF @FILETYPE = 908
			EXEC SP_IMPORT_CARI_IBM_FILE
		ELSE
		IF @FILETYPE = 909
			EXEC SP_IMPORT_PROMOSYON_IBM_FILE
		ELSE
		IF @FILETYPE = 999
			EXEC SP_IMPORT_EFATURA_FILE
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH
GO


ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R1]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
	SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	CREATE TABLE #REYONPROMOSYON(PROMOSYONID INT, REYONADI VARCHAR(20), AMIKTAR DECIMAL(21,6), VMIKTAR DECIMAL(21,6), INDYUZDE FLOAT, INDTUTAR FLOAT)
	
	INSERT INTO #REYONPROMOSYON(PROMOSYONID, REYONADI, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
	SELECT 
		P.ID,
		REYONADI,
		AMIKTAR, 
		VMIKTAR,
		INDYUZDE,
		INDTUTAR
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R1' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 
	
	IF EXISTS(SELECT TOP 1 * FROM #REYONPROMOSYON)
	BEGIN
		CREATE TABLE #INDIRIM(AREYONADI VARCHAR(20), INDIRIMTUTARI FLOAT, AMIKTAR FLOAT, VMIKTAR FLOAT)

		CREATE TABLE #FIS(
							ID INT IDENTITY(1,1) PRIMARY KEY,
							PROMOSYONID INT,
							REYONADI VARCHAR(20), 
							ASATISFIYAT FLOAT, 
							ASATISMIKTAR FLOAT, 
							ASATISTUTAR FLOAT, 
							AMIKTAR FLOAT, 
							VMIKTAR FLOAT, 
							INDYUZDE FLOAT, 
							INDTUTAR FLOAT
						)
		
		DECLARE
			@ID					INT, 
			@AREYONADI			VARCHAR(20),

			@ASATISFIYAT		FLOAT, 
			@ASATISMIKTAR		FLOAT, 
			@ASATISTUTAR		FLOAT, 

			@ALINACAKMIKTAR		FLOAT, 
			@VERILECEKMIKTAR	FLOAT, 
			@AKALANMIKTAR		FLOAT,
			@R1INDYUZDE			FLOAT,
			@R1INDTUTAR			FLOAT


		INSERT INTO #FIS(PROMOSYONID, REYONADI, ASATISFIYAT, ASATISMIKTAR, ASATISTUTAR,  AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
		SELECT 
			P.PROMOSYONID,
			S.REYONADI,
			D.FIYAT,
			SUM(D.MIKTAR) AS MIKTAR,
			SUM(D.TUTAR) AS TUTAR,
			P.AMIKTAR,
			P.VMIKTAR,
			P.INDYUZDE,
			P.INDTUTAR
		FROM TBL_BEKLETME_DETAY D
			INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
			INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI, REYONADI) S ON S.PLUNO = D.PLUNO
			INNER JOIN #REYONPROMOSYON P ON P.REYONADI COLLATE TURKISH_CI_AS = S.REYONADI 
		WHERE ISBEKLETME = 0
		GROUP BY P.PROMOSYONID, S.REYONADI, D.FIYAT, P.AMIKTAR, P.VMIKTAR, P.INDYUZDE, P.INDTUTAR
		HAVING SUM(D.MIKTAR) > 0
		ORDER BY FIYAT DESC

		DECLARE @PROMOSYONID INT
		DECLARE CURRREYON CURSOR FAST_FORWARD FOR
		SELECT PROMOSYONID FROM #FIS
		GROUP BY PROMOSYONID
		OPEN CURRREYON
		

		FETCH NEXT FROM CURRREYON
		INTO @PROMOSYONID

		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @AKALANMIKTAR = 0

			DECLARE CURR CURSOR FAST_FORWARD FOR
			SELECT 
				ID,
				REYONADI,
				ASATISFIYAT,
				ASATISMIKTAR,
				ASATISTUTAR,
				AMIKTAR,
				VMIKTAR,
				CASE WHEN INDYUZDE <= 0 THEN 100 ELSE INDYUZDE END,
				INDTUTAR
			FROM #FIS
			WHERE PROMOSYONID = @PROMOSYONID
			ORDER BY ASATISFIYAT DESC
			OPEN CURR

			FETCH NEXT FROM CURR
			INTO 
				@ID					,
				@AREYONADI			,
				@ASATISFIYAT		,
				@ASATISMIKTAR		,
				@ASATISTUTAR		,
				@ALINACAKMIKTAR		,
				@VERILECEKMIKTAR	,
				@R1INDYUZDE,
				@R1INDTUTAR

			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @AKALANMIKTAR = @AKALANMIKTAR + @ASATISMIKTAR
				
				WHILE @AKALANMIKTAR >= @ALINACAKMIKTAR 
				BEGIN
					INSERT INTO #INDIRIM(AREYONADI, INDIRIMTUTARI, AMIKTAR, VMIKTAR)
					SELECT @AREYONADI, CASE WHEN @R1INDTUTAR > 0 THEN @R1INDTUTAR ELSE ROUND(((@VERILECEKMIKTAR * @ASATISFIYAT) * @R1INDYUZDE / 100.00),2) END , @ALINACAKMIKTAR, @VERILECEKMIKTAR

					SET @AKALANMIKTAR = @AKALANMIKTAR - @ALINACAKMIKTAR
				END
	
				FETCH NEXT FROM CURR
				INTO 
					@ID					,
					@AREYONADI			,
					@ASATISFIYAT		,
					@ASATISMIKTAR		,
					@ASATISTUTAR		,
					@ALINACAKMIKTAR		,
					@VERILECEKMIKTAR	,
					@R1INDYUZDE,
					@R1INDTUTAR

			END

			CLOSE CURR
			DEALLOCATE CURR
			
			FETCH NEXT FROM CURRREYON
			INTO @PROMOSYONID
		END

		CLOSE CURRREYON
		DEALLOCATE CURRREYON

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT 
			'25',
			0,
			SUM(INDIRIMTUTARI) AS INDIRIMTUTARI,
			SUBSTRING(AREYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, SUM(AMIKTAR))+' ADET ALANA '+CONVERT(VARCHAR, SUM(VMIKTAR))+' ADET ÜRÜNDE '+CONVERT(VARCHAR, CAST(ROUND(SUM(INDIRIMTUTARI),2) AS MONEY),1)+' TL İNDİRİM',
			0
		FROM #INDIRIM
		GROUP BY AREYONADI

		DROP TABLE #FIS
		DROP TABLE #INDIRIM		
	END


	
	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #REYONPROMOSYON
	DROP TABLE #RETTABLE
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_XZ_LOG') AND name='POSKREDITOPLAMI')
ALTER TABLE dbo.TBL_XZ_LOG ADD
	POSKREDITOPLAMI float NULL
GO

ALTER PROCEDURE [dbo].[SP_XZ_REPORT]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL
AS


DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPPOSKREDITOPLAMI FLOAT	 ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPFISNO IS NOT NULL
BEGIN
	DECLARE @TEKRARFISID INT, @ONCEKIFISNO INT
	
	SELECT @TMPSONTARIH = TARIH, @TMPPOSKREDITOPLAMI = ISNULL(POSKREDITOPLAMI,0)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE FISNO = @TMPFISNO AND TIP = @TMPTIP
	
	SELECT @ONCEKIFISNO = MAX(CONVERT(INT, FISNO))
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT, FISNO) < CONVERT(INT, @TMPFISNO) AND TIP = @TMPTIP
	
	SELECT @TMPILKTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT,FISNO) = @ONCEKIFISNO AND TIP = @TMPTIP
	
	IF @TMPILKTARIH IS NULL SET @TMPILKTARIH = GETDATE() - 365
END
ELSE
BEGIN
	IF @TMPTARIH IS NULL 
		SELECT TOP 1 @TMPTARIH = MAX(TARIH)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z'
	--	ORDER BY TARIH DESC
		
		SELECT TOP 1 @TMPPOSKREDITOPLAMI = ISNULL(POSKREDITOPLAMI,0)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = @TMPTIP
		ORDER BY TARIH DESC
	
	IF @TMPFISNO IS NULL
		SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = @TMPTIP
	--	ORDER BY TARIH DESC

	SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
	SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

	IF @TMPILKTARIH IS NULL
		SET @TMPILKTARIH = @TMPTARIH
	IF @TMPSONTARIH IS NULL
		SET @TMPSONTARIH = GETDATE()
END

SET @TMPPOSKREDITOPLAMI = ISNULL(@TMPPOSKREDITOPLAMI,0)




SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DÖKÜMÜ' ELSE 'FİŞ DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DÖKÜMÜ' ELSE 'FATURA DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İRSALİYE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'BELGE İPTALLERİ ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPKDV, KDVHRC, TOPLAM, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CASE 
		WHEN ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'') <> '' THEN
		ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'')
	ELSE 'KSM'+CONVERT(VARCHAR, D.DEPARTMAN)+' (%'+CONVERT(VARCHAR, D.KDV)+' KDV)' END AS ACIKLAMA,
	SUM((CASE WHEN D.BELGETIPI = 2 THEN -1 ELSE 1 END) * D.NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL D
WHERE D.BELGETIPI IN(0,1,2,8)
GROUP BY D.DEPARTMAN, D.KDV
ORDER BY D.DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET TAHSİLAT DÖKÜMÜ(SATIŞ-İADE)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99]-PUAN',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'

DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-TAHSİLAT TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-SATIŞ TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0),
	3


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'BRÜT TAHSİLAT DÖKÜMÜ(SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(ABS(D.TUTAR)) AS TUTAR,
	11
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99]-PUAN',
	SUM(ABS(D.INDTUTAR)) AS TUTAR,
	11
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,8) AND
	D.PROMOSYONTIPI = '99'

DECLARE @TMPBRUTAHSILATTOPLAMI DECIMAL(21,6), @TMPBRUTODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPBRUTAHSILATTOPLAMI = SUM(TUTAR) 
FROM #RETTABLE
WHERE TIP = 11
 
SELECT @TMPBRUTODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-BRÜT TAHSİLAT TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0),
	11

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-BRÜT SATIŞ TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPBRUTODEMETIPIINDIRIMI),0),
	11


IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA GİRİŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA ÇIKIŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İND.TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'ARA TOPLAM İND. ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS ADET 
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME TİPİ İND. ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	SUM(INDTUTAR) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PUAN HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS ADET FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'VER.HED.ÇEK TOP.['+CONVERT(VARCHAR, ISNULL(COUNT(ID),0))+']',
	SUM(ABS(TUTAR)) AS TUTAR,
	6
FROM TBL_HEDIYE_CEK HC WITH (NOLOCK) 
WHERE TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA GİRİŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA ÇIKIŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #NAKITODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
WHERE KREDINO = 0
GROUP BY FISID

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #ODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
GROUP BY FISID

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET NAKİT TOPLAMI',
	SUM(
		(CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0)
		-(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS NAKITTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT JOIN #NAKITODEME D ON  D.FISID=M.ID 
WHERE M.TIP<> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET CİRO',
	SUM(
		((CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0))-
		(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS CIROTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT OUTER JOIN #ODEME D ON  D.FISID=M.ID 
WHERE M.TIP <> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

DROP TABLE #NAKITODEME
DROP TABLE #ODEME

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'YEMEK ÇEKİ HARİÇ KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF DEĞERLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF KDV', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF TOPLAM', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPPOSKREDITOPLAMI AS POSKREDITOPLAMI, @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


ALTER PROCEDURE [dbo].[SP_XZ_LOG_INSERT]
	@TIP	VARCHAR(1),
	@FISNO	VARCHAR(6),
	@TARIH	DATETIME,
	@TOPLAM	FLOAT,
	@TOPKDV	FLOAT,
	@KDVHRC	FLOAT,
	@ADET	FLOAT,
	@KASIYERADI	VARCHAR(50),
	@POSKREDITOPLAMI FLOAT = NULL
AS
	IF @TIP = 'Z'
	BEGIN
		DECLARE @ID INT
		SELECT @ID = MAX(ID)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'X' AND TARIH IN (
										SELECT MAX(TARIH)
										FROM TBL_XZ_LOG WITH (NOLOCK)
										WHERE TIP = 'X'
										)
		IF @ID IS NOT NULL
			UPDATE TBL_XZ_LOG
			SET TARIH = @TARIH
			WHERE ID = @ID
		ELSE
			INSERT INTO TBL_XZ_LOG(TIP, FISNO, TARIH, TOPLAM, TOPKDV, KDVHRC, ADET, KASIYERADI, POSKREDITOPLAMI)
			SELECT 'X', @FISNO, @TARIH, @TOPLAM, @TOPKDV, @KDVHRC, @ADET, @KASIYERADI, @POSKREDITOPLAMI

	END

	INSERT INTO TBL_XZ_LOG(TIP, FISNO, TARIH, TOPLAM, TOPKDV, KDVHRC, ADET, KASIYERADI, POSKREDITOPLAMI)
	SELECT @TIP, @FISNO, @TARIH, @TOPLAM, @TOPKDV, @KDVHRC, @ADET, @KASIYERADI, @POSKREDITOPLAMI
GO

ALTER PROCEDURE [dbo].[SP_IMPORT_CARI_FILE]
	@ISDEGISEN BIT = 0,
	@ISTRUNCATETABLE BIT = 1
AS
SET NOCOUNT ON


DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRY
	SELECT
		CONVERT(TINYINT, SUBSTRING(DATA,1,1)) AS FIYATTIPNO,
		CONVERT(INT, SUBSTRING(DATA,2,6)) AS CARINO,
		RTRIM(SUBSTRING(DATA,8,20)) AS CARIKODU,
		RTRIM(SUBSTRING(DATA,28,20)) AS CARIADI,
		RTRIM(SUBSTRING(DATA,48,60)) AS ADRES,
		RTRIM(SUBSTRING(DATA,108,15)) AS VERGIDAIRESI,
		RTRIM(SUBSTRING(DATA,123,15)) AS VERGINO,
		CONVERT(INT, SUBSTRING(DATA,138,2)) AS INDIRIM,
		CASE WHEN LEN(DATA) <= 140 THEN CONVERT(BIT, 0) ELSE CONVERT(BIT, ISNULL(SUBSTRING(DATA,140,1),'0')) END AS ISEFATURA,
		CASE WHEN LEN(DATA) <= 140 THEN '' ELSE RTRIM(SUBSTRING(DATA,141,50)) END AS EMAIL,
		CASE WHEN LEN(DATA) <= 140 THEN 'S' ELSE RTRIM(SUBSTRING(DATA,191,1)) END AS CARITIPI,
		CASE WHEN LEN(DATA) <= 140 THEN '-' ELSE RTRIM(SUBSTRING(DATA,192,20)) END AS TELEFON,
		CASE WHEN LEN(DATA) <= 140 THEN 'GENEL' ELSE RTRIM(SUBSTRING(DATA,212,20)) END AS GRUP,
		CONVERT(BIT, CASE WHEN LEN(DATA) <= 140 THEN 1 ELSE CASE WHEN SUBSTRING(DATA,232,1) = '0' THEN 0 ELSE 1 END END) AS ISVERESIYE,
		CONVERT(BIT, 0) AS ISINSERTTELEFON,
		CONVERT(VARCHAR(20),'') CEPTELEFONU
	INTO #TEMPFILE FROM TBL_IMPORT_FILE
	WHERE LEN(DATA) >= 139

	UPDATE #TEMPFILE
	SET CEPTELEFONU = TELEFON

	UPDATE #TEMPFILE
	SET CEPTELEFONU = ''
	WHERE 
		(CEPTELEFONU NOT LIKE '905%' AND
		CEPTELEFONU NOT LIKE '5%' AND
		CEPTELEFONU NOT LIKE '05%') OR
		LEN(CEPTELEFONU) > 17 

	DELETE FROM #TEMPFILE
	WHERE CARIKODU IN (
						SELECT CARIKODU FROM #TEMPFILE
						GROUP BY CARIKODU
						HAVING COUNT(*) > 1
						)

	UPDATE #TEMPFILE
	SET CEPTELEFONU = REPLACE(CEPTELEFONU,' ', '')
	WHERE LEN(REPLACE(CEPTELEFONU,' ', '')) >= 10

	UPDATE #TEMPFILE
	SET CEPTELEFONU = CASE WHEN SUBSTRING(CEPTELEFONU,1,2) = '05' THEN '9'+CEPTELEFONU WHEN SUBSTRING(CEPTELEFONU,1,1) = '5' THEN '90'+CEPTELEFONU ELSE CEPTELEFONU END
	WHERE LEN(CEPTELEFONU) >= 10

	UPDATE #TEMPFILE
	SET CEPTELEFONU = ''
	WHERE CEPTELEFONU NOT LIKE '905%'
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : CARİ DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : CARI DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

BEGIN TRAN

	IF @ISDEGISEN = 1
		BEGIN TRY
			DELETE FROM TBL_CARI_MAIN
			WHERE CARINO IN (SELECT CARINO FROM #TEMPFILE)

			DELETE FROM TBL_CARI_TELEFON
			WHERE CARIKODU IN (SELECT CARIKODU FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH
	ELSE
	BEGIN
		IF ISNULL(@ISTRUNCATETABLE,1) = 1
		BEGIN
			TRUNCATE TABLE TBL_CARI_MAIN
			TRUNCATE TABLE TBL_CARI_TELEFON
		END
	END

	BEGIN TRY
		INSERT INTO TBL_CARI_MAIN(CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, CREATEDATE, CREATEUSERCODE, FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, ISVERESIYE)
		SELECT CARINO, CARIKODU, CARIADI, ADRES, VERGIDAIRESI, VERGINO, INDIRIM, GRUP, GETDATE(), APP_NAME(), FIYATTIPNO, ISEFATURA, EMAIL, CARITIPI, TELEFON, ISVERESIYE
		FROM  #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		SELECT C.ID, T.CARIKODU, REPLACE(T.CEPTELEFONU,' ','') AS TELEFON, CONVERT(BIT, 0) AS ISDELETE INTO #TMP 
		FROM #TEMPFILE T WITH (NOLOCK)
			INNER JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = T.CARIKODU
		WHERE LEN(REPLACE(T.CEPTELEFONU,' ','')) >= 10 

		UPDATE #TMP
		SET TELEFON = CASE WHEN SUBSTRING(TELEFON,1,2) = '05' THEN '9'+TELEFON WHEN SUBSTRING(TELEFON,1,1) = '5' THEN '90'+TELEFON ELSE TELEFON END

		UPDATE #TMP
		SET ISDELETE = 1
		FROM #TMP C
			INNER JOIN TBL_CARI_TELEFON T WITH (NOLOCK) ON T.CARIKODU = C.CARIKODU AND T.TELEFON = C.TELEFON

		DELETE FROM #TMP
		WHERE ISDELETE = 1

		INSERT INTO TBL_CARI_TELEFON(CARIKODU, TELEFON)
		SELECT CARIKODU, TELEFON FROM #TMP
		WHERE ID IN (
						SELECT MAX(ID) FROM #TMP
						WHERE 
							TELEFON LIKE '905%' AND
							LEN(TELEFON) = 12 AND
							TELEFON NOT LIKE '%[a-z][A-Z]%'
						GROUP BY TELEFON
					) AND 
			TELEFON NOT IN (SELECT TELEFON FROM TBL_CARI_TELEFON WITH (NOLOCK)) AND
			CARIKODU NOT IN (SELECT CARIKODU FROM TBL_CARI_TELEFON WITH (NOLOCK)) 

		DROP TABLE #TMP
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_TELEFON TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	IF ISNULL((SELECT COUNT(*) FROM TBL_CARI_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_CARI_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END

COMMIT TRAN

DROP TABLE #TEMPFILE
GO
ALTER PROCEDURE [dbo].[SP_IMPORT_FILE]
	@FILENAME	NVARCHAR(500),
	@FILETYPE	INT,
	@ISTRUNCATETABLE BIT = 1
AS
	SET NOCOUNT ON
	SET @ISTRUNCATETABLE = ISNULL(@ISTRUNCATETABLE,1)
	DECLARE
		@DURUM		TINYINT,
		@ACIKLAMA	VARCHAR(MAX),
		@ISERROR	BIT	,
		@DOSYAADI	VARCHAR(MAX)

	TRUNCATE TABLE TBL_IMPORT_FILE

	BEGIN TRY
		DECLARE @sql NVARCHAR(4000) = 'BULK INSERT TBL_IMPORT_FILE FROM ''' + @FILENAME + ''' WITH (ROWTERMINATOR = ''0x0A'', CODEPAGE = ''1254'')';
		EXEC(@sql);
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN (BULK INSERT) HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		IF @FILETYPE = 107
			EXEC SP_IMPORT_URUN_FILE 0, @ISTRUNCATETABLE
		ELSE
		IF @FILETYPE = 1071
			EXEC SP_IMPORT_URUN_FILE 1
		ELSE
		IF @FILETYPE = 108
			EXEC SP_IMPORT_CARI_FILE 0, @ISTRUNCATETABLE
		ELSE
		IF @FILETYPE = 1081
			EXEC SP_IMPORT_CARI_FILE 1
		ELSE
		IF @FILETYPE = 109
			EXEC SP_IMPORT_KASIYER_FILE
		ELSE
		IF @FILETYPE = 110
			EXEC SP_IMPORT_DOVIZ_FILE
		ELSE
		IF @FILETYPE = 126
			EXEC SP_IMPORT_REYON_FILE
		ELSE
		IF @FILETYPE = 113
			EXEC SP_IMPORT_PROMOSYON_FILE
		ELSE
		IF @FILETYPE = 138
			EXEC SP_IMPORT_OZELKOD_FILE
		ELSE
		IF @FILETYPE = 907
			EXEC SP_IMPORT_URUN_IBM_FILE
		ELSE
		IF @FILETYPE = 908
			EXEC SP_IMPORT_CARI_IBM_FILE
		ELSE
		IF @FILETYPE = 909
			EXEC SP_IMPORT_PROMOSYON_IBM_FILE
		ELSE
		IF @FILETYPE = 999
			EXEC SP_IMPORT_EFATURA_FILE
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH
GO
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_FIS_MAIN') AND name='ORDERNO')
ALTER TABLE dbo.TBL_FIS_MAIN ADD
	ORDERNO varchar(50) NULL
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_BEKLETME_MAIN') AND name='ORDERNO')
ALTER TABLE dbo.TBL_BEKLETME_MAIN ADD
	ORDERNO varchar(50) NULL
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_MAIN_INSERT_UPDATE]
	@ID				INT = NULL,
	@ISBEKLETME		BIT,
	@KASANO			INT,
	@BELGEKODU		VARCHAR(20),
	@TARIH			DATETIME,
	@TIP			TINYINT,
	@VERGINO		VARCHAR(20),
	@CARIKODU		VARCHAR(20),
	@CARIADI		VARCHAR(50),
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@ISEFATURA		BIT,
	@ALIAS			VARCHAR(MAX),
	@YETKILIKODU	VARCHAR(4) = NULL,
	@YETKILIADI		VARCHAR(20) = NULL,
	@OKCNO			VARCHAR(20) = NULL,
	@ACIKLAMA		VARCHAR(MAX) = NULL,
	@ORDERNO		VARCHAR(50)	= NULL
AS
	SET NOCOUNT ON
	IF ISNULL(@ID,0) = 0
	BEGIN
		IF @ISBEKLETME = 0
			IF EXISTS(SELECT TOP 1 ID FROM TBL_BEKLETME_MAIN WITH (NOLOCK) WHERE ISBEKLETME = 0)
			BEGIN
				DELETE FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
			END
	
		INSERT INTO TBL_BEKLETME_MAIN(ISBEKLETME, KASANO, BELGEKODU, TARIH, TIP, VERGINO, CARIKODU, CARIADI, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, ISEFATURA, ALIAS, YETKILIKODU, YETKILIADI, OKCNO, ACIKLAMA, ORDERNO)
		SELECT @ISBEKLETME, @KASANO, @BELGEKODU, @TARIH, @TIP, @VERGINO, @CARIKODU, @CARIADI, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @ISEFATURA, @ALIAS, @YETKILIKODU, @YETKILIADI, @OKCNO, @ACIKLAMA, @ORDERNO

		RETURN @@IDENTITY
	END
	ELSE
	BEGIN
		DELETE FROM TBL_BEKLETME_LOG WHERE FISID = @ID

		UPDATE TBL_BEKLETME_MAIN
		SET
			ISBEKLETME	= @ISBEKLETME	,
			KASANO		= @KASANO		,
			BELGEKODU	= @BELGEKODU	,
			TARIH		= @TARIH		,
			TIP			= @TIP			,
			VERGINO		= @VERGINO		,
			CARIKODU	= @CARIKODU		,
			CARIADI		= @CARIADI		,
			TUTAR		= @TUTAR		,
			INDYUZDE	= @INDYUZDE		,
			INDTUTAR	= @INDTUTAR		,
			ARTYUZDE	= @ARTYUZDE		,
			ARTTUTAR	= @ARTTUTAR		,
			KASIYERKODU	= @KASIYERKODU	,
			KASIYERADI	= @KASIYERADI	,
			ISEFATURA	= @ISEFATURA	,
			ALIAS		= @ALIAS		,
			YETKILIKODU	= @YETKILIKODU	,
			YETKILIADI	= @YETKILIADI	,
			OKCNO		= @OKCNO		,
			ACIKLAMA	= @ACIKLAMA		,
			ORDERNO		= @ORDERNO
		WHERE ID = @ID

		RETURN @ID
	END
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_MAIN_LIST]
	@ID	INT = NULL,
	@ISBEKLETME BIT = NULL,
	@BELGEKODU VARCHAR(20) = NULL
AS

	SELECT
		B.ID,
		B.ISBEKLETME,
		B.KASANO,
		B.BELGEKODU,
		B.TARIH,
		B.TIP,
		B.VERGINO,
		B.CARIKODU,
		B.CARIADI,
		ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
		B.TUTAR,
		B.INDYUZDE,
		B.INDTUTAR,
		B.ARTYUZDE,
		B.ARTTUTAR,
		B.KASIYERKODU,
		B.KASIYERADI,
		B.ISEFATURA,
		B.ALIAS,
		B.YETKILIKODU,
		B.YETKILIADI,
		B.OKCNO,
		ISNULL(C.ISVERESIYE,0) AS ISVERESIYE,
		ISNULL(B.ACIKLAMA,'') AS ACIKLAMA,
		B.ORDERNO
	FROM TBL_BEKLETME_MAIN B WITH (NOLOCK)
		LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = B.CARIKODU
	WHERE
		B.ID = ISNULL(@ID, B.ID) AND
		B.ISBEKLETME = ISNULL(@ISBEKLETME, B.ISBEKLETME) AND
		B.BELGEKODU = ISNULL(@BELGEKODU, B.BELGEKODU)
GO


ALTER PROCEDURE [dbo].[SP_FIS_MAIN_INSERT]
	@KASANO			INT,
	@BELGEKODU		VARCHAR(20),
	@TARIH			DATETIME,
	@TIP			TINYINT,
	@VERGINO		VARCHAR(20),
	@CARIKODU		VARCHAR(20),
	@CARIADI		VARCHAR(50),
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PARAUSTU		FLOAT,
	@ISEFATURA		BIT,
	@EFATURAKODU	VARCHAR(20),
	@UUID			VARCHAR(50),
	@ALIAS			VARCHAR(MAX),
	@PUAN			FLOAT,
	@ISSENDPUAN		BIT,
	@ACIKLAMA		VARCHAR(MAX) = NULL,
	@YETKILIKODU	VARCHAR(4) = NULL,
	@YETKILIADI		VARCHAR(20) = NULL,
	@OKCFISNO		VARCHAR(50) = NULL,
	@ORDERNO		VARCHAR(50) = NULL
AS
	SET NOCOUNT ON

	INSERT INTO TBL_FIS_MAIN(KASANO, BELGEKODU, TARIH, TIP, VERGINO, CARIKODU, CARIADI, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PARAUSTU, ISEFATURA, EFATURAKODU, UUID, ALIAS, PUAN, ISSENDPUAN, ACIKLAMA, YETKILIKODU, YETKILIADI, OKCFISNO, ORDERNO)
	SELECT @KASANO, @BELGEKODU, @TARIH, @TIP, @VERGINO, @CARIKODU, @CARIADI, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PARAUSTU, @ISEFATURA, @EFATURAKODU, @UUID, @ALIAS, @PUAN, @ISSENDPUAN, @ACIKLAMA, @YETKILIKODU, @YETKILIADI, @OKCFISNO, @ORDERNO

	RETURN @@IDENTITY
GO

ALTER PROCEDURE [dbo].[SP_FIS_MAIN_LIST]
	@ID		INT = NULL,
	@FISBARKOD VARCHAR(20) = NULL,
	@ILKTARIH	SMALLDATETIME = NULL,
	@SONTARIH	SMALLDATETIME = NULL,
	@ISSEND		BIT = NULL,
	@ISHARICI	BIT = NULL
AS
	CREATE TABLE #RETTABLE(
		ID INT, KASANO INT, BELGEKODU VARCHAR(20), TARIH DATETIME, TIP TINYINT, VERGINO VARCHAR(20), CARIKODU VARCHAR(20), CARIADI VARCHAR(50), TUTAR FLOAT, 
		INDYUZDE FLOAT, INDTUTAR FLOAT, ARTYUZDE FLOAT, ARTTUTAR FLOAT, KASIYERKODU VARCHAR(4), KASIYERADI VARCHAR(50), PARAUSTU FLOAT, ISEFATURA BIT, FIYATTIPNO INT, 
		EFATURAKODU VARCHAR(20), UUID VARCHAR(50), TYPE VARCHAR(20), ALIAS VARCHAR(200), YETKILIKODU VARCHAR(4), YETKILIADI VARCHAR(50),
		ACIKLAMA VARCHAR(MAX), ORDERNO VARCHAR(50)
	)

	IF @ID IS NOT NULL
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA,
			ORDERNO
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA,
			F.ORDERNO
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
 		WHERE F.ID = @ID
	ELSE IF @FISBARKOD IS NOT NULL
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA,
			ORDERNO
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA,
			F.ORDERNO
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE SUBSTRING(CONVERT(VARCHAR, F.TARIH, 112)+REPLACE(CONVERT(VARCHAR, F.TARIH, 114),':',''),1,14) = SUBSTRING(@FISBARKOD,1,14)
	ELSE IF ISNULL(@ISSEND,1) = 0
	BEGIN
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA,
			ORDERNO
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA,
			F.ORDERNO
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE 
			((ISSEND IS NULL OR ISSEND = 0) OR (@ISHARICI = 1)) AND
			CONVERT(VARCHAR, F.TARIH, 112) >= CONVERT(VARCHAR, @ILKTARIH, 112) AND
			CONVERT(VARCHAR, F.TARIH, 112) <= CONVERT(VARCHAR, @SONTARIH, 112) 
	END
	ELSE
		INSERT INTO #RETTABLE(
			ID,
			KASANO,
			BELGEKODU,
			TARIH,
			TIP,
			VERGINO,
			CARIKODU,
			CARIADI,
			TUTAR,
			INDYUZDE,
			INDTUTAR,
			ARTYUZDE,
			ARTTUTAR,
			KASIYERKODU,
			KASIYERADI,
			PARAUSTU,
			ISEFATURA,
			FIYATTIPNO,
			EFATURAKODU,
			UUID,
			ALIAS,
			YETKILIKODU,
			YETKILIADI,
			ACIKLAMA,
			ORDERNO
		)
		SELECT
			F.ID,
			F.KASANO,
			F.BELGEKODU,
			F.TARIH,
			F.TIP,
			F.VERGINO,
			F.CARIKODU,
			F.CARIADI,
			F.TUTAR,
			F.INDYUZDE,
			F.INDTUTAR,
			F.ARTYUZDE,
			F.ARTTUTAR,
			F.KASIYERKODU,
			F.KASIYERADI,
			F.PARAUSTU,
			F.ISEFATURA,
			ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
			F.EFATURAKODU,
			F.UUID,
			F.ALIAS,
			F.YETKILIKODU,
			F.YETKILIADI,
			F.ACIKLAMA,
			F.ORDERNO
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = F.CARIKODU
		WHERE 
			CONVERT(VARCHAR, F.TARIH, 112) >= CONVERT(VARCHAR, @ILKTARIH, 112) AND
			CONVERT(VARCHAR, F.TARIH, 112) <= CONVERT(VARCHAR, @SONTARIH, 112) 
		
	UPDATE #RETTABLE
	SET TYPE = E.TYPE
	FROM #RETTABLE R
		INNER JOIN TBL_CARI_EFATURA E WITH (NOLOCK) ON E.ALIAS = R.ALIAS
	WHERE R.ISEFATURA = 1

	SELECT * FROM #RETTABLE
	ORDER BY ID ASC

	DROP TABLE #RETTABLE
GO


ALTER PROCEDURE [dbo].[SP_IMPORT_PROMOSYON_FILE]
	@ISTRUNCATETABLE BIT = 1
AS

SET DATEFORMAT mdy 

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRAN

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, SUBSTRING(DATA,6,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,9,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,16,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,19,10),'.',''))/100 AS INDTUTAR,
			1 AS VMIKTAR,
			0 AS VPLUNO,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			SUBSTRING(DATA,74,20) AS REYONADI,
			CONVERT(INT, SUBSTRING(DATA,95,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,101,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP
		INTO #TEMPFILE FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P2'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	IF ISNULL(@ISTRUNCATETABLE,1) = 1
	BEGIN
		TRUNCATE TABLE TBL_PROMOSYON_URUN
		TRUNCATE TABLE TBL_PROMOSYON_TUTAR
		TRUNCATE TABLE TBL_PROMOSYON_REYON
		TRUNCATE TABLE TBL_PROMOSYON_LIMIT
	END

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ISNULL(REYONADI,''), PUAN, CARIGRUP
		FROM #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	DROP TABLE #TEMPFILE 
	
	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,17,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,20,10),'.',''))/100 AS INDTUTAR,
			SUBSTRING(DATA,32,1) AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,74,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,80,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,101,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE2 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P1'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 0, 0, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, PUANYUZDE
		FROM #TEMPFILE2
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE2
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE2

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,27,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,31,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,46,2)+'-'+SUBSTRING(DATA,43,2)+SUBSTRING(DATA,48,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,66,2)+'-'+SUBSTRING(DATA,63,2)+SUBSTRING(DATA,68,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,83,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,89,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(BIT, SUBSTRING(DATA,110,1)) AS TUMURUNLER,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,112,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE3 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P4') AND CONVERT(INT, SUBSTRING(DATA,20,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, TUMURUNLER, PUANYUZDE
		FROM #TEMPFILE3
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE3
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE3

	BEGIN TRY
		SELECT
			'P4' AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,17,6)) AS VPLUNO,
			0 AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,79,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,85,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,105,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE4 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PF') AND CONVERT(INT, SUBSTRING(DATA,17,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, 0, PUANYUZDE
		FROM #TEMPFILE4
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE4
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE4

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			RTRIM(SUBSTRING(DATA,79,20)) AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,100,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,106,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, SUBSTRING(DATA,127,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,131,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE5 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PR') AND RTRIM(SUBSTRING(DATA,79,20)) <> ''
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE
		FROM #TEMPFILE5
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE5
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE5

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(INT, SUBSTRING(DATA,6,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,13,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,16,6)) AS VPLUNO,
			CONVERT(FLOAT, REPLACE(REPLACE(SUBSTRING(DATA,23,2),'--','0'),' ','0')) AS VMIKTAR, 
			CONVERT(FLOAT, SUBSTRING(DATA,26,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,29,10),'.',''))/100 AS INDTUTAR,
			CONVERT(DATETIME, SUBSTRING(DATA,44,2)+'-'+SUBSTRING(DATA,41,2)+SUBSTRING(DATA,46,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,64,2)+'-'+SUBSTRING(DATA,61,2)+SUBSTRING(DATA,66,14)) AS BITISTARIHI,
			'' AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,81,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,87,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP
		INTO #TEMPFILE6 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P3') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP
		FROM #TEMPFILE6
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE6
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE6

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			RTRIM(SUBSTRING(DATA,6,20)) AS REYONADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,38,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,42,10),'.',''))/100 AS INDTUTAR,
			CONVERT(INT, SUBSTRING(DATA,53,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,60,2)) AS VMIKTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,92,2)+'-'+SUBSTRING(DATA,89,2)+SUBSTRING(DATA,94,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,112,2)+'-'+SUBSTRING(DATA,109,2)+SUBSTRING(DATA,114,14)) AS BITISTARIHI,
			CONVERT(FLOAT, SUBSTRING(DATA,129,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,132,5)) AS PUAN,
			CONVERT(BIT, SUBSTRING(DATA,138,1)) AS ISKADEMELI,
			RTRIM(SUBSTRING(DATA,140,255)) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,396,20)) AS VREYONADI
		INTO #TEMPFILE7 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P7')  OR SUBSTRING(DATA,1,1) IN ('R')
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P7 VEYA R PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_REYON(PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, CARIGRUP, VREYONADI)
		SELECT
			PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, CARIGRUP, VREYONADI
		FROM #TEMPFILE7
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE7
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P VEYA R TBL_PROMOSYON_REYON TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE7

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(INT, SUBSTRING(DATA,6,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,6,20)) AS REYONADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,13,10),',','.')) AS LIMIT,
			CONVERT(INT, SUBSTRING(DATA,24,2)) AS FIYATTIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,30,2)+'-'+SUBSTRING(DATA,27,2)+SUBSTRING(DATA,32,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,50,2)+'-'+SUBSTRING(DATA,47,2)+SUBSTRING(DATA,52,14)) AS BITISTARIHI
		INTO #TEMPFILE8 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P8') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P8 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_LIMIT(BASLANGICTARIHI, BITISTARIHI, CARITIPI, PLUNO, LIMIT, FIYATTIPI)
		SELECT
			BASLANGICTARIHI, BITISTARIHI, CARITIPI, PLUNO, LIMIT, FIYATTIPI
		FROM #TEMPFILE8
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE8
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P8 TBL_PROMOSYON_LIMIT TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE8
COMMIT TRAN
GO

ALTER PROCEDURE [dbo].[SP_IMPORT_PROMOSYON_IBM_FILE]
	@ISTRUNCATETABLE BIT = 1
AS

SET DATEFORMAT mdy 

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)

BEGIN TRAN

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, SUBSTRING(DATA,6,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,9,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,16,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,19,10),'.',''))/100 AS INDTUTAR,
			1 AS VMIKTAR,
			0 AS VPLUNO,
			'' AS VSTOKKODU,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			SUBSTRING(DATA,74,20) AS REYONADI,
			CONVERT(INT, SUBSTRING(DATA,95,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,101,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,122,20)) AS STOKKODU
		INTO #TEMPFILE FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P2'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	IF ISNULL(@ISTRUNCATETABLE,1) = 1
	BEGIN
		TRUNCATE TABLE TBL_PROMOSYON_URUN
		TRUNCATE TABLE TBL_PROMOSYON_TUTAR
		TRUNCATE TABLE TBL_PROMOSYON_REYON
	END
	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP, STOKKODU, VSTOKKODU)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ISNULL(REYONADI,''), PUAN, CARIGRUP, STOKKODU, VSTOKKODU
		FROM #TEMPFILE
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P2 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	DROP TABLE #TEMPFILE 
	
	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,17,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,20,10),'.',''))/100 AS INDTUTAR,
			SUBSTRING(DATA,32,1) AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,37,2)+'-'+SUBSTRING(DATA,34,2)+SUBSTRING(DATA,39,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,57,2)+'-'+SUBSTRING(DATA,54,2)+SUBSTRING(DATA,59,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,74,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,80,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,101,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE2 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) = 'P1'
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 0, 0, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, PUANYUZDE
		FROM #TEMPFILE2
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE2
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P1 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE2

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,27,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,31,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,46,2)+'-'+SUBSTRING(DATA,43,2)+SUBSTRING(DATA,48,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,66,2)+'-'+SUBSTRING(DATA,63,2)+SUBSTRING(DATA,68,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,83,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,89,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(BIT, SUBSTRING(DATA,110,1)) AS TUMURUNLER,
			RTRIM(SUBSTRING(DATA,112,20)) AS VSTOKKODU,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,133,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE3 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P4') AND CONVERT(INT, SUBSTRING(DATA,20,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	
	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, VSTOKKODU, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, TUMURUNLER, VSTOKKODU, PUANYUZDE
		FROM #TEMPFILE3
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE3
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P4 TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE3

	BEGIN TRY
		SELECT
			'P4' AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,17,6)) AS VPLUNO,
			0 AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			CONVERT(INT, SUBSTRING(DATA,79,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,85,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,106,20)) AS VSTOKKODU,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,127,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE4 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PF') AND CONVERT(INT, SUBSTRING(DATA,17,6)) <> 0
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, TUMURUNLER, VSTOKKODU, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, '', ODEMETIPI, PUAN, 0, VSTOKKODU, PUANYUZDE
		FROM #TEMPFILE4
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE4
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PF TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	DROP TABLE #TEMPFILE4

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,6,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(INT, SUBSTRING(DATA,20,6)) AS VPLUNO,
			0 AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS INDTUTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,42,2)+'-'+SUBSTRING(DATA,39,2)+SUBSTRING(DATA,44,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,62,2)+'-'+SUBSTRING(DATA,59,2)+SUBSTRING(DATA,64,14)) AS BITISTARIHI,
			RTRIM(SUBSTRING(DATA,79,20)) AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,100,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,106,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,127,10),'.',''))/100 AS PUANYUZDE
		INTO #TEMPFILE5 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('PR') AND RTRIM(SUBSTRING(DATA,79,20)) <> ''
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_TUTAR(PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, VSTOKKODU, PUANYUZDE)
		SELECT
			PROMOSYONTIPI, CARITIPI, ARATOPLAM, INDYUZDE, INDTUTAR, 1, VPLUNO, CARIGRUP, BASLANGICTARIHI, BITISTARIHI, VREYONADI, ODEMETIPI, PUAN, '', PUANYUZDE
		FROM #TEMPFILE5
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE5
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : PR TBL_PROMOSYON_TUTAR TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE5

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			CONVERT(INT, SUBSTRING(DATA,6,6)) AS PLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,13,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,16,6)) AS VPLUNO,
			CONVERT(FLOAT, REPLACE(REPLACE(SUBSTRING(DATA,23,2),'--','0'),' ','0')) AS VMIKTAR, 
			CONVERT(FLOAT, SUBSTRING(DATA,26,2)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,29,10),'.',''))/100 AS INDTUTAR,
			CONVERT(DATETIME, SUBSTRING(DATA,44,2)+'-'+SUBSTRING(DATA,41,2)+SUBSTRING(DATA,46,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,64,2)+'-'+SUBSTRING(DATA,61,2)+SUBSTRING(DATA,66,14)) AS BITISTARIHI,
			'' AS VREYONADI,
			CONVERT(INT, SUBSTRING(DATA,81,5)) AS PUAN,
			RTRIM(REPLACE(REPLACE(SUBSTRING(DATA,87,20),CHAR(13),''),CHAR(10), '')) AS CARIGRUP,
			RTRIM(SUBSTRING(DATA,108,20)) AS STOKKODU,
			RTRIM(SUBSTRING(DATA,129,20)) AS VSTOKKODU
		INTO #TEMPFILE6 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P3') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_URUN(PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP, STOKKODU, VSTOKKODU)
		SELECT
			PROMOSYONTIPI, CARITIPI, AMIKTAR, PLUNO, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, VREYONADI, PUAN, CARIGRUP, STOKKODU, VSTOKKODU
		FROM #TEMPFILE6
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE6
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P3 TBL_PROMOSYON_URUN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE6

	BEGIN TRY
		SELECT
			SUBSTRING(DATA,1,2) AS PROMOSYONTIPI,
			SUBSTRING(DATA,4,1) AS CARITIPI,
			RTRIM(SUBSTRING(DATA,6,20)) AS REYONADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,27,10),'.',''))/100 AS ARATOPLAM,
			CONVERT(FLOAT, SUBSTRING(DATA,38,3)) AS INDYUZDE,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,42,10),'.',''))/100 AS INDTUTAR,
			CONVERT(INT, SUBSTRING(DATA,53,6)) AS VPLUNO,
			CONVERT(FLOAT, SUBSTRING(DATA,60,2)) AS VMIKTAR,
			'' AS ODEMETIPI,
			CONVERT(DATETIME, SUBSTRING(DATA,92,2)+'-'+SUBSTRING(DATA,89,2)+SUBSTRING(DATA,94,14)) AS BASLANGICTARIHI,
			CONVERT(DATETIME, SUBSTRING(DATA,112,2)+'-'+SUBSTRING(DATA,109,2)+SUBSTRING(DATA,114,14)) AS BITISTARIHI,
			CONVERT(FLOAT, SUBSTRING(DATA,129,2)) AS AMIKTAR,
			CONVERT(INT, SUBSTRING(DATA,132,5)) AS PUAN,
			CONVERT(BIT, SUBSTRING(DATA,138,1)) AS ISKADEMELI,
			RTRIM(SUBSTRING(DATA,140,20)) AS VSTOKKODU,
			RTRIM(SUBSTRING(DATA,161,255)) AS CARIGRUP
		INTO #TEMPFILE7 FROM TBL_IMPORT_FILE
		WHERE SUBSTRING(DATA,1,2) IN ('P7') 
	END TRY
	BEGIN CATCH
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P7 PROMOSYONUNUN PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		INSERT INTO TBL_PROMOSYON_REYON(PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, VSTOKKODU, CARIGRUP)
		SELECT
			PROMOSYONTIPI, CARITIPI, REYONADI, ARATOPLAM, AMIKTAR, INDYUZDE, INDTUTAR, VMIKTAR, VPLUNO, BASLANGICTARIHI, BITISTARIHI, ODEMETIPI, PUAN, ISKADEMELI, VSTOKKODU, CARIGRUP
		FROM #TEMPFILE7
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE7
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : P7 TBL_PROMOSYON_REYON TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH


	DROP TABLE #TEMPFILE7

COMMIT TRAN
GO

ALTER PROCEDURE [dbo].[SP_IMPORT_FILE]
	@FILENAME	NVARCHAR(500),
	@FILETYPE	INT,
	@ISTRUNCATETABLE BIT = 1
AS
	SET NOCOUNT ON
	SET @ISTRUNCATETABLE = ISNULL(@ISTRUNCATETABLE,1)
	DECLARE
		@DURUM		TINYINT,
		@ACIKLAMA	VARCHAR(MAX),
		@ISERROR	BIT	,
		@DOSYAADI	VARCHAR(MAX)

	TRUNCATE TABLE TBL_IMPORT_FILE

	BEGIN TRY
		DECLARE @sql NVARCHAR(4000) = 'BULK INSERT TBL_IMPORT_FILE FROM ''' + @FILENAME + ''' WITH (ROWTERMINATOR = ''0x0A'', CODEPAGE = ''1254'')';
		EXEC(@sql);
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN (BULK INSERT) HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH

	BEGIN TRY
		IF @FILETYPE = 107
			EXEC SP_IMPORT_URUN_FILE 0, @ISTRUNCATETABLE
		ELSE
		IF @FILETYPE = 1071
			EXEC SP_IMPORT_URUN_FILE 1
		ELSE
		IF @FILETYPE = 108
			EXEC SP_IMPORT_CARI_FILE 0, @ISTRUNCATETABLE
		ELSE
		IF @FILETYPE = 1081
			EXEC SP_IMPORT_CARI_FILE 1
		ELSE
		IF @FILETYPE = 109
			EXEC SP_IMPORT_KASIYER_FILE
		ELSE
		IF @FILETYPE = 110
			EXEC SP_IMPORT_DOVIZ_FILE
		ELSE
		IF @FILETYPE = 126
			EXEC SP_IMPORT_REYON_FILE
		ELSE
		IF @FILETYPE = 113
			EXEC SP_IMPORT_PROMOSYON_FILE @ISTRUNCATETABLE
		ELSE
		IF @FILETYPE = 138
			EXEC SP_IMPORT_OZELKOD_FILE
		ELSE
		IF @FILETYPE = 907
			EXEC SP_IMPORT_URUN_IBM_FILE
		ELSE
		IF @FILETYPE = 908
			EXEC SP_IMPORT_CARI_IBM_FILE
		ELSE
		IF @FILETYPE = 909
			EXEC SP_IMPORT_PROMOSYON_IBM_FILE @ISTRUNCATETABLE
		ELSE
		IF @FILETYPE = 999
			EXEC SP_IMPORT_EFATURA_FILE
	END TRY
	BEGIN CATCH
		SET @ACIKLAMA = @FILENAME+' İSİMLİ DOSYA IMPORT EDİLİRKEN HATA :'+ERROR_MESSAGE()
		RAISERROR(@ACIKLAMA,16,1)
		RETURN
	END CATCH
GO

ALTER PROCEDURE [dbo].[SP_XZ_REPORT_EARCHIVE]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL,
	@NORMALMODE	BIT = NULL
AS


DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPTARIH IS NULL 
	SELECT TOP 1 @TMPTARIH = MAX(TARIH)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = 'Z'
--	ORDER BY TARIH DESC

IF @TMPFISNO IS NULL
	SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = @TMPTIP
--	ORDER BY TARIH DESC

SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

IF @TMPILKTARIH IS NULL
	SET @TMPILKTARIH = @TMPTARIH
IF @TMPSONTARIH IS NULL
	SET @TMPSONTARIH = GETDATE()


IF @TMPFISNO IS NOT NULL
BEGIN
	DECLARE @TEKRARFISID INT, @ONCEKIFISNO INT
	
	SELECT @TMPSONTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE FISNO = @TMPFISNO AND TIP = @TMPTIP
	
	SELECT @ONCEKIFISNO = MAX(CONVERT(INT, FISNO))
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT, FISNO) < CONVERT(INT, @TMPFISNO) AND TIP = @TMPTIP
	
	SELECT @TMPILKTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT,FISNO) = @ONCEKIFISNO AND TIP = @TMPTIP
	
	IF @TMPILKTARIH IS NULL SET @TMPILKTARIH = GETDATE() - 365
END

CREATE TABLE #FISTABLE(ID INT PRIMARY KEY)

IF ISNULL(@NORMALMODE,0) = 0
	INSERT INTO #FISTABLE(ID)
	SELECT ID FROM TBL_FIS_MAIN WITH (NOLOCK)
ELSE
BEGIN
	SELECT FISID INTO #ODEMETABLE FROM TBL_FIS_ODEME WITH (NOLOCK)
	GROUP BY FISID
	HAVING MAX(KREDINO) > 0

	INSERT INTO #FISTABLE(ID)
	SELECT ID FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE 
		ID IN (SELECT FISID FROM #ODEMETABLE) OR
		CARIKODU <> '' OR
		TIP > 0

	DROP TABLE #ODEMETABLE
END


SELECT * INTO #FISMAIN FROM TBL_FIS_MAIN WITH (NOLOCK)
WHERE 
	ID IN (SELECT ID FROM #FISTABLE) 

SELECT * INTO #FISDETAY FROM TBL_FIS_DETAY WITH (NOLOCK)
WHERE FISID IN (SELECT ID FROM #FISTABLE)

SELECT * INTO #FISODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
WHERE FISID IN (SELECT ID FROM #FISTABLE)

SELECT * INTO #FISPROMOSYON FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
WHERE FISID IN (SELECT ID FROM #FISTABLE)

DROP TABLE #FISTABLE

SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM #FISDETAY D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM #FISDETAY D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'Z DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM #FISMAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DÖKÜMÜ' ELSE 'FİŞ DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM #FISMAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DÖKÜMÜ' ELSE 'FATURA DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İRSALİYE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'BELGE İPTALLERİ ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPKDV, KDVHRC, TOPLAM, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KSM'+CONVERT(VARCHAR, DEPARTMAN)+' (%'+CONVERT(VARCHAR, KDV)+' KDV)' AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2,8)
GROUP BY DEPARTMAN, KDV
ORDER BY DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAHSİLAT DÖKÜMÜ (SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3
FROM #FISODEME D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - PUAN',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3
FROM #FISPROMOSYON D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'



DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998] - TAHSİLAT TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999] - SATIŞ TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0),
	3

IF EXISTS(
			SELECT TOP 1 ID FROM #FISMAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA GİRİŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM #FISMAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA ÇIKIŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İND.TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'ARA TOPLAM İND. ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS ADET 
		FROM #FISMAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM #FISPROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM #FISPROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME TİPİ İND. ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	SUM(INDTUTAR) AS PTUTAR ,
	6
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PUAN HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS ADET FROM #FISMAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA GİRİŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA ÇIKIŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'YEMEK ÇEKİ HARİÇ KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM #FISODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF DEĞERLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF KDV', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF TOPLAM', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
DROP TABLE #FISMAIN
DROP TABLE #FISDETAY
DROP TABLE #FISODEME
DROP TABLE #FISPROMOSYON
GO
ALTER PROCEDURE [dbo].[SP_HAREKET_LIST]
	@TIP	VARCHAR(2) = NULL, --HR, HD, HI
	@KASANO	INT = NULL,
	@TARIH	SMALLDATETIME = NULL,
	@INTERFORMAT	BIT = NULL,
	@REMOVEBARPOSFORMATS BIT = NULL,
	@ISMAXMIKTAR	BIT = NULL
AS
	SET DATEFORMAT mdy; 

	IF  @TIP IS NULL
	BEGIN
		SET @TIP = 'HR'
		SET @KASANO = 1
		SET @TARIH = '03/28/2024'
		SET @REMOVEBARPOSFORMATS = 0
		SET @INTERFORMAT = 0
		SET @ISMAXMIKTAR=1
	END

DECLARE
	@AY		INT,
	@YIL	INT,
	@GUN	INT

SELECT
	@GUN	= DATEPART(DD, @TARIH),
	@AY		= DATEPART(MM, @TARIH),
	@YIL	= DATEPART(YY, @TARIH)

CREATE TABLE #HRTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, BELGEID INT, TIP INT, SATIRNO INT, PLASIYERKODU VARCHAR(4), DATA VARCHAR(MAX), TARIH DATETIME, TOPLAM FLOAT, CARIKODU VARCHAR(20), TIPNO INT, YETKILIKODU VARCHAR(4), YETKILIADI VARCHAR(20), EFATURAKODU VARCHAR(20), UUID VARCHAR(50), ISEFATURA BIT)
IF @TIP = 'TO'
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 6 THEN 'T,N,00,'
				WHEN 7 THEN 'O,N,00,'
			END+
			dbo.SR(CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END,20)+','+
			dbo.SR(BELGEKODU,20)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		TIP IN (6, 7)

	SELECT DATA FROM #HRTABLE
END
ELSE
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, YETKILIKODU, YETKILIADI, EFATURAKODU, UUID, ISEFATURA)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 0 THEN '01,FIS'
				WHEN 1 THEN '02,FAT'
				WHEN 8 THEN '46,IRS'
				WHEN 2 THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 1 THEN '24,GPS' ELSE '21,FAT' END
			ELSE '01,FIS' END+','+
			dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+'     '+
			dbo.ZL(KASIYERKODU,4)+','+
			dbo.ZL(CONVERT(VARCHAR,BELGEKODU),6)+'  '+
			dbo.ZL(CONVERT(VARCHAR,KASIYERKODU),4),
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1, 
		YETKILIKODU, 
		YETKILIADI,
		EFATURAKODU,
		UUID,
		ISEFATURA
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		(
		((@TIP = 'HR') AND (TIP IN (0, 1, 8))) OR
		(((@TIP = 'HD') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 0)) OR
		(((@TIP = 'HR') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 1)) OR
		((@TIP = 'HI') AND (TIP IN (3)))
		)


	CREATE TABLE #DETAY(ID INT, PLUNO INT, BARKOD VARCHAR(20), ISDELETE BIT)

	INSERT INTO #DETAY(ID, PLUNO, BARKOD, ISDELETE)
	SELECT ID, PLUNO, BARKOD, 0
	FROM TBL_FIS_DETAY D
	WHERE D.FISID IN (SELECT ID FROM #HRTABLE)

	UPDATE #DETAY
	SET ISDELETE = 1
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN S ON S.BARKOD = D.BARKOD

	DELETE FROM #DETAY	WHERE ISDELETE = 1

	UPDATE #DETAY SET ISDELETE = 1

	UPDATE #DETAY
	SET BARKOD = M.BARKOD,
		ISDELETE = 0
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN M ON M.PLUNO = D.PLUNO

	DELETE FROM #DETAY WHERE ISDELETE = 1

	UPDATE TBL_FIS_DETAY
	SET BARKOD = D.BARKOD
	FROM TBL_FIS_DETAY F WITH (NOLOCK)
		INNER JOIN #DETAY D ON D.ID = F.ID

	DROP TABLE #DETAY

	SELECT FISID
	INTO #ODEME FROM TBL_FIS_ODEME
	WHERE 
		FISID IN (SELECT BELGEID FROM #HRTABLE) AND 
		KREDINO = 39
	GROUP BY FISID

	IF @TIP = 'HR'
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO)
		SELECT
			ID,
			TIP,
			9999999,
				CASE TIP
					WHEN 4 THEN '13,KGR'
				ELSE '12,KCK' END+',000000'+
				dbo.ZL(CONVERT(VARCHAR,BELGEKODU),4)+'00,'+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
			TARIH,
			TUTAR,
			CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
			1
		FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE
			KASANO = @KASANO AND
			DATEPART(DD, TARIH) = @GUN AND
			DATEPART(MM, TARIH) = @AY AND
			DATEPART(YY, TARIH) = @YIL AND
			TIP IN (4, 5)
	END

	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		TIP,
		2,
		'03,TAR,'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(DD, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(MM, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(YY, TARIH)),4)+'  ,'+
		dbo.SR(LEFT(CONVERT(VARCHAR, TARIH, 114),8),12),
		2
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
	SELECT
		D.FISID,
		MIN(SATIRNO)+2,
			CASE D.TIP
				WHEN 'SAT' THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN CASE WHEN M.TIP = 2 THEN '05' ELSE '04' END ELSE CASE WHEN M.TIP = 2 THEN '25' ELSE '04' END END
				WHEN 'IPT' THEN '05'
			ELSE '04' END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN D.TIP ELSE CASE WHEN M.TIP = 2 THEN CASE WHEN D.TIP = 'SAT' THEN 'GAL' ELSE 'IPT' END ELSE D.TIP END END+','+
			dbo.ZL(CONVERT(VARCHAR, 
									CASE 
										WHEN ABS(SUM(MIKTAR)) < 99.999 THEN CONVERT(DECIMAL(5,3), ROUND(ABS(SUM(MIKTAR)),3,1)) 
										WHEN ABS(SUM(MIKTAR)) < 999.99 THEN CONVERT(DECIMAL(5,2), ROUND(ABS(SUM(MIKTAR)),2,1)) 
										WHEN ABS(SUM(MIKTAR)) < 9999.9 THEN CONVERT(DECIMAL(5,1), ROUND(ABS(SUM(MIKTAR)),1,1)) 
										WHEN ABS(SUM(MIKTAR)) < 99999 THEN CONVERT(DECIMAL(5,0), ROUND(ABS(SUM(MIKTAR)),0,1)) 
									ELSE CONVERT(DECIMAL(5,3), ABS(SUM(MIKTAR))) END),6)+
			dbo.ZL(CONVERT(VARCHAR,PLUNO),6)+','+
			dbo.ZL(CONVERT(VARCHAR,DEPARTMAN),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(SUM(D.TUTAR)))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(SUM(D.TUTAR)) AS money), 0),10) END,
			D.PLASIYERKODU,
			3
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND D.TIP IN ('SAT', 'IPT')
	GROUP BY D.FISID, M.TIP, D.TIP, D.PLUNO, D.BARKOD, D.DEPARTMAN, D.PLASIYERKODU 
	ORDER BY D.FISID, MIN(SATIRNO)

	IF (ISNULL(@INTERFORMAT,0) = 1)
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
		SELECT
			D.FISID,
			MIN(SATIRNO)+2,
				'38,BKD,'+
				dbo.SR(SUBSTRING(BARKOD,1,12),12)+','+dbo.SR(SUBSTRING(BARKOD,13,8),12),
				D.PLASIYERKODU,
				4
		FROM TBL_FIS_DETAY D WITH (NOLOCK)
		WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT', 'IPT')
		GROUP BY D.FISID, D.TIP, D.BARKOD, D.PLASIYERKODU
		ORDER BY D.FISID


		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> '' AND TIPNO = 3
	END
	ELSE
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> ''  AND TIPNO = 3


	SELECT MIN(ID) AS ID, D.FISID, D.PLUNO, MIN(SATIRNO) AS SATIRNO, CONVERT(VARCHAR(10), '') AS KASIYERKODU
	INTO #FISDETAY FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') 
	GROUP BY D.FISID, D.PLUNO
	ORDER BY D.FISID, MIN(SATIRNO)
	
	UPDATE  #FISDETAY
	SET KASIYERKODU = D.KASIYERKODU
	FROM #FISDETAY F
		INNER JOIN TBL_FIS_DETAY D WITH (NOLOCK) ON D.ID = F.ID

	SELECT FISID, ISNULL(PLUNO,0) AS PLUNO, SUM(INDTUTAR) AS INDTUTAR INTO #PROMOSYON FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
	WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
	GROUP BY FISID, ISNULL(PLUNO,0)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		D.SATIRNO+2,
			'06'+',IND,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			6
	FROM #FISDETAY D
		INNER JOIN #PROMOSYON P ON P.FISID = D.FISID AND P.PLUNO = D.PLUNO

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		SATIRNO+2,
			'39'+',ART,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		7
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') AND ARTTUTAR <> 0
	ORDER BY D.FISID, D.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'06'+',IND,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			8
	FROM TBL_FIS_MAIN F WITH (NOLOCK)
		INNER JOIN #PROMOSYON P ON P.FISID = F.ID AND P.PLUNO = 0
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND P.INDTUTAR <> 0
	ORDER BY ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'39'+',ART,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		8
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND ARTTUTAR <> 0
	ORDER BY ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			10001,
				'53'+',PRM,'+ dbo.ZL(P.PROMOSYONTIPI,2)+'    '+CASE WHEN ISNULL(PLUNO,0) > 0 THEN dbo.ZL(CONVERT(VARCHAR, PLUNO),6) ELSE '    '+CASE WHEN KREDINO > 0 THEN dbo.ZL(CONVERT(VARCHAR,KREDINO),2) ELSE '  ' END END+','+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			9
		FROM TBL_FIS_PROMOSYON P WITH (NOLOCK)
			INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = P.FISID
		WHERE P.FISID IN (SELECT BELGEID FROM #HRTABLE) 
		ORDER BY P.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		20001,
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN '08,TOP,            ,'
		ELSE CASE WHEN TIP = 3 THEN '30,FIP,           0,' ELSE '08,TOP,            ,' END END
		+
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),MAX(ABS(TOPLAM)))*100,0))),12)
		ELSE dbo.SL(CONVERT(VARCHAR, CAST(MAX(ABS(TOPLAM)) AS money), 0),12) END,
		10
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)
	GROUP BY BELGEID, TIP

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		FISID,
		2000001+ID,
		CASE KREDINO
			WHEN 0 THEN '09,NAK,            ,'
		ELSE '10,KRD,          '+dbo.ZL(CONVERT(VARCHAR, KREDINO),2)+',' END+
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
		ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
		11
	FROM TBL_FIS_ODEME WITH (NOLOCK)
	WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
	ORDER BY FISID, ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT 
			H.BELGEID,
			A.SATIRNO,
			'77,ONY,'+
			dbo.SR(YETKILIKODU,4)+dbo.SR(SUBSTRING(YETKILIADI,1,8),8)+','+
			dbo.SR(SUBSTRING(YETKILIADI,9,12),12),
			12
		FROM #HRTABLE H
			INNER JOIN (
						SELECT
							BELGEID,
							MAX(SATIRNO)+1 AS SATIRNO
						FROM #HRTABLE
						GROUP BY BELGEID
					   ) AS A ON A.BELGEID = H.BELGEID
		WHERE ISNULL(YETKILIKODU,'') <> ''
	
	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'44,'+CASE WHEN ISNULL(ISEFATURA,0) = 1 THEN 'EFK' ELSE 'EAK' END+','+ 
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5) AND ISNULL(EFATURAKODU,'') <> ''
		GROUP BY BELGEID, ISNULL(ISEFATURA,0), ISNULL(EFATURAKODU,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'55,'+'UI1'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+2,
			'55,'+'UI2'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),21,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),33,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			3000001+K.ID,
			'77,'+'KDV'+','+ 
			dbo.ZL(CONVERT(VARCHAR, KDV),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVTUTAR))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVTUTAR) AS money), 0),10) END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVHARICTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVHARICTUTAR) AS money), 0),12) END,
			12
		FROM TBL_FIS_KDV K WITH (NOLOCK)
		WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
		ORDER BY FISID, KDV

	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		H.BELGEID,
		MAX(H.SATIRNO)+1,
		'11,SON,'+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),1,12),12)+','+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),13,8),8)+'   '+CASE WHEN O.FISID IS NULL THEN ' ' ELSE 'A' END,
		13
	FROM #HRTABLE H
		LEFT JOIN #ODEME O ON O.FISID = H.BELGEID
	WHERE ISNULL(H.TIP,0) NOT IN (4,5,10)
	GROUP BY H.BELGEID, ISNULL(H.CARIKODU,''), O.FISID

	IF @REMOVEBARPOSFORMATS = 0
		IF @TIP = 'HR'
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA,TIPNO)
		SELECT
			9999999+ID,
			9999999+ID,
			'16,ZRP,'+
			dbo.SR(CONVERT(VARCHAR, @TARIH, 103),12)+','+
			dbo.SR(SUBSTRING(CONVERT(VARCHAR, TARIH, 114),1,8),12),
			14
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z' AND TARIH >= @TARIH AND TARIH < @TARIH+1

	SELECT '1,'+dbo.ZL(CONVERT(VARCHAR, ROW_NUMBER() OVER(ORDER BY BELGEID, SATIRNO, TIPNO, DATA)),5)+ ',' + DATA AS DATA FROM #HRTABLE

	DROP TABLE #FISDETAY
	DROP TABLE #PROMOSYON
	DROP TABLE #ODEME
END


DROP TABLE #HRTABLE
GO
ALTER PROCEDURE [dbo].[SP_CARI_EFATURA_LIST]
	@IDENTIFIER	VARCHAR(MAX), 
	@AKTIF		BIT 
AS
		SELECT 
			C.ID, 
			C.ALIAS, 
			C.CREATEDATE, 
			C.IDENTIFIER, 
			C.AKTIF, 
			C.TITLE, 
			C.TYPE, 
			C.UPDATEDATE,
			ISNULL((SELECT ISNULL(EMAIL,'') FROM TBL_CARI_MAIN M WITH (NOLOCK) WHERE VERGINO = @IDENTIFIER),'')  AS EMAIL,
			ISNULL((SELECT ISNULL(VERGIDAIRESI,'') FROM TBL_CARI_MAIN M WITH (NOLOCK) WHERE VERGINO = @IDENTIFIER),'')  AS VERGIDAIRESI
		FROM TBL_CARI_EFATURA C WITH (NOLOCK)
		WHERE 
			C.IDENTIFIER = @IDENTIFIER AND
			C.AKTIF = @AKTIF
GO
ALTER PROCEDURE [dbo].[SP_BEKLETME_MAIN_LIST]
	@ID	INT = NULL,
	@ISBEKLETME BIT = NULL,
	@BELGEKODU VARCHAR(20) = NULL
AS

	SELECT
		B.ID,
		B.ISBEKLETME,
		B.KASANO,
		B.BELGEKODU,
		B.TARIH,
		B.TIP,
		B.VERGINO,
		B.CARIKODU,
		B.CARIADI,
		ISNULL(C.FIYATTIPNO, 1) AS FIYATTIPNO,
		B.TUTAR,
		B.INDYUZDE,
		B.INDTUTAR,
		B.ARTYUZDE,
		B.ARTTUTAR,
		B.KASIYERKODU,
		B.KASIYERADI,
		B.ISEFATURA,
		B.ALIAS,
		B.YETKILIKODU,
		B.YETKILIADI,
		B.OKCNO,
		ISNULL(C.ISVERESIYE,0) AS ISVERESIYE,
		ISNULL(B.ACIKLAMA,'') AS ACIKLAMA,
		B.ORDERNO,
		ISNULL(C.EMAIL,'') AS EMAIL,
		ISNULL(C.VERGIDAIRESI,'') AS VERGIDAIRESI
	FROM TBL_BEKLETME_MAIN B WITH (NOLOCK)
		LEFT JOIN TBL_CARI_MAIN C WITH (NOLOCK) ON C.CARIKODU = B.CARIKODU
	WHERE
		B.ID = ISNULL(@ID, B.ID) AND
		B.ISBEKLETME = ISNULL(@ISBEKLETME, B.ISBEKLETME) AND
		B.BELGEKODU = ISNULL(@BELGEKODU, B.BELGEKODU)
GO

ALTER PROCEDURE [dbo].[SP_CARI_EFATURA_LIST] 
	@IDENTIFIER	VARCHAR(MAX), 
	@AKTIF		BIT 
AS
		SELECT 
			C.ID, 
			C.ALIAS, 
			C.CREATEDATE, 
			C.IDENTIFIER, 
			C.AKTIF, 
			C.TITLE, 
			C.TYPE, 
			C.UPDATEDATE,
			ISNULL((SELECT TOP 1 ISNULL(EMAIL,'') FROM TBL_CARI_MAIN M WITH (NOLOCK) WHERE VERGINO = @IDENTIFIER AND ISNULL(EMAIL, '') <> ''),'')  AS EMAIL,
			ISNULL((SELECT TOP 1 ISNULL(VERGIDAIRESI,'') FROM TBL_CARI_MAIN M WITH (NOLOCK) WHERE VERGINO = @IDENTIFIER AND ISNULL(VERGIDAIRESI,'') <> ''),'')  AS VERGIDAIRESI
		FROM TBL_CARI_EFATURA C WITH (NOLOCK)
		WHERE 
			C.IDENTIFIER = @IDENTIFIER AND
			C.AKTIF = @AKTIF
GO

ALTER PROCEDURE [dbo].[SP_IMPORT_URUN_FILE]
	@ISDEGISEN BIT = 0,
	@ISTRUNCATETABLE BIT = 1
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)
CREATE TABLE #TEMPFILE(
						PLUNO INT, 
						BARKOD VARCHAR(20), 
						STOKADI VARCHAR(50), 
						FIYAT FLOAT, 
						DEPARTMAN INT,
						BIRIM VARCHAR(4),
						TARTILI VARCHAR(1),
						FIYAT2 FLOAT,
						FIYAT3 FLOAT,
						DOVIZKODU VARCHAR(10),
						ALISDEPARTMAN INT,
						STOKKODU VARCHAR(20),
						REYONADI VARCHAR(20),
						RENK VARCHAR(50),
						BEDEN VARCHAR(20),
						MODELKODU VARCHAR(20),
						TEVKIFATKODU VARCHAR(10),
						TEVKIFATACIKLAMA VARCHAR(100),
						TEVKIFATORANI INT,
						OTVKODU VARCHAR(10),
						OTVACIKLAMA VARCHAR(100),
						OTVORANI INT,
						ALISFIYAT FLOAT,
						ISINDIRIM BIT
					)
BEGIN TRY
	
--IF EXISTS(
--				SELECT TOP 1 1 FROM TBL_IMPORT_FILE 
--				WHERE PATINDEX('%[Ã‡]%', DATA COLLATE Latin1_General_bin) > 0
--			)
--	UPDATE TBL_IMPORT_FILE
--	SET DATA = dbo.utf8_to_utf16(DATA)

	DECLARE @DATA VARCHAR(MAX)

	SELECT TOP 1 @DATA = DATA FROM TBL_IMPORT_FILE
	
	IF LEN(@DATA) <= 82
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,20)) AS STOKADI,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,10),'.',''))/100 
			ELSE CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,9),'.',''))/100 END AS FIYAT,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(INT, SUBSTRING(DATA,58,2)) 
			ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS DEPARTMAN,
			CASE WHEN LEN(DATA) = 65 THEN 
				RTRIM(SUBSTRING(DATA,60,4)) 
			ELSE
				RTRIM(SUBSTRING(DATA,59,4)) END AS BIRIM,
			
			CASE WHEN LEN(DATA) = 65 THEN 
				SUBSTRING(DATA,64,1)
			ELSE
				SUBSTRING(DATA,63,1) END AS TARTILI,
			0 AS FIYAT2,
			0 AS FIYAT3,
			'TL' AS DOVIZKODU,
			CASE WHEN LEN(DATA) = 65 THEN CONVERT(INT, SUBSTRING(DATA,58,2)) ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,8,20)) AS STOKKODU,
			'' AS REYONADI,
			'' AS RENK,
			'' AS BEDEN,
			'' AS MODELKODU,
			'' AS TEVKIFATKODU,
			'' AS TEVKIFATACIKLAMA,
			0  AS TEVKIFATORANI,
			'' AS OTVKODU,
			'' AS OTVACIKLAMA,
			0  AS OTVORANI,
			0 AS ALISFIYAT,
			1 AS ISINDIRIM
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63 AND LEN(@DATA) = LEN(DATA)
	ELSE
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,50)) AS STOKADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,78,9),'.',''))/100 AS FIYAT,
			CONVERT(INT, SUBSTRING(DATA,87,2)) AS DEPARTMAN,
			RTRIM(SUBSTRING(DATA,89,4)) AS BIRIM,
			SUBSTRING(DATA,93,1) AS TARTILI,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,94,9),'.',''),'0')) / 100 AS FIYAT2,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,103,9),'.',''),'0')) / 100 AS FIYAT3,
			RTRIM(SUBSTRING(DATA,112,10)) AS DOVIZKODU,
			CONVERT(INT, SUBSTRING(DATA,122,2)) AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,124,20)) AS STOKKODU,
			RTRIM(SUBSTRING(DATA,144,20)) AS REYONADI,
			RTRIM(SUBSTRING(DATA,164,50)) AS RENK,
			RTRIM(SUBSTRING(DATA,214,20)) AS BEDEN,
			RTRIM(SUBSTRING(DATA,234,20)) AS MODELKODU,
			RTRIM(SUBSTRING(DATA,254,10)) AS TEVKIFATKODU,
			RTRIM(SUBSTRING(DATA,264,100)) AS TEVKIFATACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,364,3)) AS TEVKIFATORANI,
			RTRIM(SUBSTRING(DATA,367,10)) AS OTVKODU,
			RTRIM(SUBSTRING(DATA,377,100)) AS OTVACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,477,3)) AS OTVORANI,
			CONVERT(FLOAT, ISNULL(REPLACE(REPLACE(REPLACE(SUBSTRING(DATA,480,9),'.',''),CHAR(13),'0'),CHAR(10),'0'),'0'))/100 AS ALISFIYAT,
			CONVERT(BIT, CASE WHEN SUBSTRING(DATA,489,1) = '0' THEN 0 ELSE 1 END) AS ISINDIRIM
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63  AND LEN(@DATA) = LEN(DATA)
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : ÜRÜN DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

DELETE FROM #TEMPFILE
WHERE BARKOD IN (
                                                SELECT BARKOD FROM #TEMPFILE
                                                GROUP BY BARKOD
                                                HAVING COUNT(*) > 1
                                        )

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : URUN DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

DECLARE @DEPARTMAN INT

SELECT TOP 1 @DEPARTMAN = DEPARTMAN
FROM #TEMPFILE
WHERE DEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU DEPARTMAN TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

SET @DEPARTMAN = NULL

SELECT TOP 1 @DEPARTMAN = ALISDEPARTMAN
FROM #TEMPFILE
WHERE ALISDEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU ALIŞ DEPARTMANI TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE WHERE PLUNO = 0),0) > 1
BEGIN
	SET @ERRORMESSAGE = 'HATA : PLU NUMARASI SIFIR OLAN ÜRÜNLER MEVCUT.!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

CREATE TABLE #TMPREYON(PLUNO INT, REYONADI VARCHAR(20))

IF LEN(@DATA) <= 80
	INSERT INTO #TMPREYON(PLUNO, REYONADI)
	SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN WITH (NOLOCK)
	GROUP BY PLUNO, REYONADI

BEGIN TRAN

	IF @ISDEGISEN = 1
	BEGIN
		BEGIN TRY
			DELETE FROM TBL_STOK_MAIN
			WHERE PLUNO IN (SELECT PLUNO FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH

		BEGIN TRY
			DELETE FROM TBL_STOK_MAIN
			WHERE BARKOD IN (SELECT BARKOD FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH

		BEGIN TRY
			DELETE FROM TBL_STOK_KOD
			WHERE BARKOD IN (SELECT BARKOD FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK KOD TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH
	END
	ELSE
	BEGIN
		IF ISNULL(@ISTRUNCATETABLE,1) = 1
		BEGIN
			TRUNCATE TABLE TBL_STOK_MAIN
			TRUNCATE TABLE TBL_STOK_KOD
		END
	END

	BEGIN TRY
		INSERT INTO TBL_STOK_MAIN(PLUNO, BARKOD, STOKADI, DEPARTMAN, KDV, BIRIM, FIYAT, FIYAT2, FIYAT3, TARTILI, CREATEDATE, CREATEUSERCODE, DOVIZKODU, ALISDEPARTMAN, ALISKDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM)
		SELECT T.PLUNO, T.BARKOD, T.STOKADI, T.DEPARTMAN, D.KDV, T.BIRIM, T.FIYAT, CASE WHEN ISNULL(T.FIYAT2,0) = 0 THEN T.FIYAT ELSE T.FIYAT2 END, CASE WHEN ISNULL(T.FIYAT3,0) = 0 THEN T.FIYAT ELSE T.FIYAT3 END, T.TARTILI, GETDATE(), APP_NAME(), DOVIZKODU, T.ALISDEPARTMAN, A.KDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM FROM #TEMPFILE T
			INNER JOIN TBL_DEPARTMAN D WITH (NOLOCK) ON D.DEPARTMAN = T.DEPARTMAN
			INNER JOIN TBL_DEPARTMAN A WITH (NOLOCK) ON A.DEPARTMAN = T.ALISDEPARTMAN
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	BEGIN TRY
		SELECT BARKOD, STOKKODU, CONVERT(BIT,0) AS ISDELETE INTO #STOKKOD FROM #TEMPFILE
		GROUP BY BARKOD, STOKKODU

		UPDATE #STOKKOD
		SET ISDELETE = 1
		FROM #STOKKOD S
			INNER JOIN TBL_STOK_KOD K WITH (NOLOCK) ON K.BARKOD = S.BARKOD 

		INSERT INTO TBL_STOK_KOD(BARKOD, STOKKODU)
		SELECT BARKOD, STOKKODU FROM #STOKKOD
		WHERE ISDELETE = 0
		GROUP BY BARKOD, STOKKODU
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	IF LEN(@DATA) <= 80
		UPDATE TBL_STOK_MAIN 
		SET REYONADI = R.REYONADI
		FROM TBL_STOK_MAIN S
			INNER JOIN #TMPREYON R ON R.PLUNO = S.PLUNO	
	
	IF ISNULL((SELECT COUNT(*) FROM TBL_STOK_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END
	
DROP TABLE #TEMPFILE
DROP TABLE #TMPREYON

COMMIT TRAN
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_DETAY_INSERT]
	@ID				INT	= NULL,
	@FISID			INT,
	@SATIRNO		INT,
	@TIP			VARCHAR(3),
	@PLUNO			INT,
	@BARKOD			VARCHAR(20),
	@STOKKODU		VARCHAR(20),
	@STOKADI		VARCHAR(50),
	@KDV			FLOAT,
	@DEPARTMAN		INT,
	@MIKTAR			FLOAT,
	@BIRIM			VARCHAR(10),
	@FIYAT			FLOAT,
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PLASIYERKODU	VARCHAR(4),
	@PLASIYERADI	VARCHAR(20),
	@ACIKLAMA		VARCHAR(MAX),
	@BARKODTYPE		TINYINT,
	@DOVIZKODU		VARCHAR(10),
	@DOVIZKURU		FLOAT,
	@DOVIZTUTARI	FLOAT,
	@PUAN			FLOAT,
	@TEVKIFATKODU	VARCHAR(10),
	@TEVKIFATACIKLAMA VARCHAR(100),
	@TEVKIFATORANI	INT,
	@OTVKODU	VARCHAR(10),
	@OTVACIKLAMA VARCHAR(100),
	@OTVORANI	INT
AS
	SET NOCOUNT ON
--SATIRNO OLUNCA HATA OLUYORDU YANLISLIKA UPDATE YAPIYORDU
--		SELECT @ID = ID FROM TBL_BEKLETME_DETAY WITH (NOLOCK)
--		WHERE FISID = @FISID AND SATIRNO = @SATIRNO
	IF ISNULL(@ID,0) = 0
		INSERT INTO TBL_BEKLETME_DETAY(FISID, SATIRNO, TIP, PLUNO, BARKOD, STOKKODU, STOKADI, KDV, DEPARTMAN, MIKTAR, BIRIM, FIYAT, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PLASIYERKODU, PLASIYERADI, ACIKLAMA, BARKODTYPE, DOVIZKODU, DOVIZKURU, DOVIZTUTARI, PUAN, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI)
		SELECT @FISID, @SATIRNO, @TIP, @PLUNO, @BARKOD, @STOKKODU, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PLASIYERKODU, @PLASIYERADI, @ACIKLAMA, @BARKODTYPE, @DOVIZKODU, @DOVIZKURU, @DOVIZTUTARI, @PUAN, @TEVKIFATKODU, @TEVKIFATACIKLAMA, @TEVKIFATORANI, @OTVKODU, @OTVACIKLAMA, @OTVORANI
	ELSE
		UPDATE TBL_BEKLETME_DETAY
		SET
			TIP				= @TIP				,
			PLUNO			= @PLUNO			,
			BARKOD			= @BARKOD			,
			STOKKODU		= @STOKKODU			,
			STOKADI			= @STOKADI			,
			KDV				= @KDV				,
			DEPARTMAN		= @DEPARTMAN		,
			MIKTAR			= @MIKTAR			,
			BIRIM			= @BIRIM			,
			FIYAT			= @FIYAT			,
			TUTAR			= @TUTAR			,
			INDYUZDE		= @INDYUZDE			,
			INDTUTAR		= @INDTUTAR			,
			ARTYUZDE		= @ARTYUZDE			,
			ARTTUTAR		= @ARTTUTAR			,
			KASIYERKODU		= @KASIYERKODU		,
			KASIYERADI		= @KASIYERADI		,
			PLASIYERKODU	= @PLASIYERKODU		,
			PLASIYERADI		= @PLASIYERADI		,
			ACIKLAMA		= @ACIKLAMA			,
			BARKODTYPE		= @BARKODTYPE		,
			DOVIZKODU		= @DOVIZKODU		, 
			DOVIZKURU		= @DOVIZKURU		, 
			DOVIZTUTARI		= @DOVIZTUTARI		,
			PUAN			= @PUAN				,
			TEVKIFATKODU	= @TEVKIFATKODU		,
			TEVKIFATACIKLAMA= @TEVKIFATACIKLAMA	,
			TEVKIFATORANI	= @TEVKIFATORANI	,
			OTVKODU			= @OTVKODU			,
			OTVACIKLAMA		= @OTVACIKLAMA		,
			OTVORANI		= @OTVORANI			
		WHERE ID = @ID
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_DETAY_INSERT]
	@ID				INT	= NULL,
	@FISID			INT,
	@SATIRNO		INT,
	@TIP			VARCHAR(3),
	@PLUNO			INT,
	@BARKOD			VARCHAR(20),
	@STOKKODU		VARCHAR(20),
	@STOKADI		VARCHAR(50),
	@KDV			FLOAT,
	@DEPARTMAN		INT,
	@MIKTAR			FLOAT,
	@BIRIM			VARCHAR(10),
	@FIYAT			FLOAT,
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PLASIYERKODU	VARCHAR(4),
	@PLASIYERADI	VARCHAR(20),
	@ACIKLAMA		VARCHAR(MAX),
	@BARKODTYPE		TINYINT,
	@DOVIZKODU		VARCHAR(10),
	@DOVIZKURU		FLOAT,
	@DOVIZTUTARI	FLOAT,
	@PUAN			FLOAT,
	@TEVKIFATKODU	VARCHAR(10),
	@TEVKIFATACIKLAMA VARCHAR(100),
	@TEVKIFATORANI	INT,
	@OTVKODU	VARCHAR(10),
	@OTVACIKLAMA VARCHAR(100),
	@OTVORANI	INT
AS
	SET NOCOUNT ON
--SATIRNO OLUNCA HATA OLUYORDU YANLISLIKA UPDATE YAPIYORDU
--		SELECT @ID = ID FROM TBL_BEKLETME_DETAY WITH (NOLOCK)
--		WHERE FISID = @FISID AND SATIRNO = @SATIRNO
	IF ISNULL(@ID,0) > 0
		IF NOT EXISTS(SELECT TOP 1 ID FROM TBL_BEKLETME_DETAY WITH (NOLOCK) WHERE ID = @ID)
			SET @ID = NULL

	IF ISNULL(@ID,0) = 0
		INSERT INTO TBL_BEKLETME_DETAY(FISID, SATIRNO, TIP, PLUNO, BARKOD, STOKKODU, STOKADI, KDV, DEPARTMAN, MIKTAR, BIRIM, FIYAT, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PLASIYERKODU, PLASIYERADI, ACIKLAMA, BARKODTYPE, DOVIZKODU, DOVIZKURU, DOVIZTUTARI, PUAN, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI)
		SELECT @FISID, @SATIRNO, @TIP, @PLUNO, @BARKOD, @STOKKODU, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PLASIYERKODU, @PLASIYERADI, @ACIKLAMA, @BARKODTYPE, @DOVIZKODU, @DOVIZKURU, @DOVIZTUTARI, @PUAN, @TEVKIFATKODU, @TEVKIFATACIKLAMA, @TEVKIFATORANI, @OTVKODU, @OTVACIKLAMA, @OTVORANI
	ELSE
		UPDATE TBL_BEKLETME_DETAY
		SET
			TIP				= @TIP				,
			PLUNO			= @PLUNO			,
			BARKOD			= @BARKOD			,
			STOKKODU		= @STOKKODU			,
			STOKADI			= @STOKADI			,
			KDV				= @KDV				,
			DEPARTMAN		= @DEPARTMAN		,
			MIKTAR			= @MIKTAR			,
			BIRIM			= @BIRIM			,
			FIYAT			= @FIYAT			,
			TUTAR			= @TUTAR			,
			INDYUZDE		= @INDYUZDE			,
			INDTUTAR		= @INDTUTAR			,
			ARTYUZDE		= @ARTYUZDE			,
			ARTTUTAR		= @ARTTUTAR			,
			KASIYERKODU		= @KASIYERKODU		,
			KASIYERADI		= @KASIYERADI		,
			PLASIYERKODU	= @PLASIYERKODU		,
			PLASIYERADI		= @PLASIYERADI		,
			ACIKLAMA		= @ACIKLAMA			,
			BARKODTYPE		= @BARKODTYPE		,
			DOVIZKODU		= @DOVIZKODU		, 
			DOVIZKURU		= @DOVIZKURU		, 
			DOVIZTUTARI		= @DOVIZTUTARI		,
			PUAN			= @PUAN				,
			TEVKIFATKODU	= @TEVKIFATKODU		,
			TEVKIFATACIKLAMA= @TEVKIFATACIKLAMA	,
			TEVKIFATORANI	= @TEVKIFATORANI	,
			OTVKODU			= @OTVKODU			,
			OTVACIKLAMA		= @OTVACIKLAMA		,
			OTVORANI		= @OTVORANI			
		WHERE ID = @ID
GO

ALTER PROCEDURE [dbo].[SP_REYON_PROMOSYON_R1]
	@CARITIPI		VARCHAR(1) = 'H',
	@CARIGRUP		VARCHAR(255) = NULL
AS
	SET NOCOUNT ON

	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)

	CREATE TABLE #REYONPROMOSYON(PROMOSYONID INT, REYONADI VARCHAR(20), AMIKTAR DECIMAL(21,6), VMIKTAR DECIMAL(21,6), INDYUZDE FLOAT, INDTUTAR FLOAT)
	
	INSERT INTO #REYONPROMOSYON(PROMOSYONID, REYONADI, AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
	SELECT 
		P.ID,
		REYONADI,
		AMIKTAR, 
		VMIKTAR,
		INDYUZDE,
		INDTUTAR
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'R1' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) 

	IF EXISTS(SELECT TOP 1 * FROM #REYONPROMOSYON)
	BEGIN
		CREATE TABLE #INDIRIM(ID INT IDENTITY(1,1) PRIMARY KEY, SIRANO INT, AREYONADI VARCHAR(20), INDIRIMTUTARI FLOAT, AMIKTAR FLOAT, VMIKTAR FLOAT)

		CREATE TABLE #FIS(
							ID INT IDENTITY(1,1) PRIMARY KEY,
							PROMOSYONID INT,
							REYONADI VARCHAR(20), 
							ASATISFIYAT FLOAT, 
							ASATISMIKTAR FLOAT, 
							ASATISTUTAR FLOAT, 
							AMIKTAR FLOAT, 
							VMIKTAR FLOAT, 
							INDYUZDE FLOAT, 
							INDTUTAR FLOAT
						)
		
		DECLARE
			@ID					INT, 
			@AREYONADI			VARCHAR(20),

			@ASATISFIYAT		FLOAT, 
			@ASATISMIKTAR		FLOAT, 
			@ASATISTUTAR		FLOAT, 

			@ALINACAKMIKTAR		FLOAT, 
			@VERILECEKMIKTAR	FLOAT, 
			@AKALANMIKTAR		FLOAT,
			@R1INDYUZDE			FLOAT,
			@R1INDTUTAR			FLOAT



		INSERT INTO #FIS(PROMOSYONID, REYONADI, ASATISFIYAT, ASATISMIKTAR, ASATISTUTAR,  AMIKTAR, VMIKTAR, INDYUZDE, INDTUTAR)
		SELECT 
			P.PROMOSYONID,
			S.REYONADI,
			D.FIYAT,
			SUM(D.MIKTAR) AS MIKTAR,
			SUM(D.TUTAR) AS TUTAR,
			P.AMIKTAR,
			P.VMIKTAR,
			P.INDYUZDE,
			P.INDTUTAR
		FROM TBL_BEKLETME_DETAY D
			INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
			INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK)  WHERE ISNULL(REYONADI,'') <> 'NOBONUS'  AND (ISNULL(ISINDIRIM,1) = 1)  GROUP BY PLUNO, STOKADI, REYONADI) S ON S.PLUNO = D.PLUNO
			INNER JOIN #REYONPROMOSYON P ON P.REYONADI COLLATE TURKISH_CI_AS = S.REYONADI 
		WHERE ISBEKLETME = 0
		GROUP BY P.PROMOSYONID, S.REYONADI, D.FIYAT, P.AMIKTAR, P.VMIKTAR, P.INDYUZDE, P.INDTUTAR
		HAVING SUM(D.MIKTAR) > 0 
		ORDER BY FIYAT DESC

		DECLARE @PROMOSYONID INT
		DECLARE CURRREYON CURSOR FAST_FORWARD FOR
		SELECT PROMOSYONID FROM #FIS
		GROUP BY PROMOSYONID
		OPEN CURRREYON
		

		FETCH NEXT FROM CURRREYON
		INTO @PROMOSYONID

		WHILE @@FETCH_STATUS = 0
		BEGIN
			SET @AKALANMIKTAR = 0

			DECLARE CURR CURSOR FAST_FORWARD FOR
			SELECT 
				ID,
				REYONADI,
				ASATISFIYAT,
				ASATISMIKTAR,
				ASATISTUTAR,
				AMIKTAR,
				VMIKTAR,
				CASE WHEN INDYUZDE <= 0 THEN 100 ELSE INDYUZDE END,
				INDTUTAR
			FROM #FIS
			WHERE PROMOSYONID = @PROMOSYONID
			ORDER BY ASATISFIYAT DESC
			OPEN CURR

			FETCH NEXT FROM CURR
			INTO 
				@ID					,
				@AREYONADI			,
				@ASATISFIYAT		,
				@ASATISMIKTAR		,
				@ASATISTUTAR		,
				@ALINACAKMIKTAR		,
				@VERILECEKMIKTAR	,
				@R1INDYUZDE,
				@R1INDTUTAR

			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @AKALANMIKTAR = @AKALANMIKTAR + @ASATISMIKTAR
				
				WHILE @AKALANMIKTAR >= @ALINACAKMIKTAR 
				BEGIN
					INSERT INTO #INDIRIM(AREYONADI, INDIRIMTUTARI, AMIKTAR, VMIKTAR)
					SELECT @AREYONADI, CASE WHEN @R1INDTUTAR > 0 THEN @R1INDTUTAR ELSE ROUND(((@VERILECEKMIKTAR * @ASATISFIYAT) * @R1INDYUZDE / 100.00),2) END , @ALINACAKMIKTAR, @VERILECEKMIKTAR

					SET @AKALANMIKTAR = @AKALANMIKTAR - @ALINACAKMIKTAR
				END
	
				FETCH NEXT FROM CURR
				INTO 
					@ID					,
					@AREYONADI			,
					@ASATISFIYAT		,
					@ASATISMIKTAR		,
					@ASATISTUTAR		,
					@ALINACAKMIKTAR		,
					@VERILECEKMIKTAR	,
					@R1INDYUZDE,
					@R1INDTUTAR

			END

			CLOSE CURR
			DEALLOCATE CURR
			
			FETCH NEXT FROM CURRREYON
			INTO @PROMOSYONID
		END

		CLOSE CURRREYON
		DEALLOCATE CURRREYON

		UPDATE #INDIRIM
		SET SIRANO = H.SATIRNO
		FROM #INDIRIM I
			INNER JOIN (SELECT ROW_NUMBER() OVER(PARTITION BY AREYONADI ORDER BY AMIKTAR DESC) AS SATIRNO, * FROM #INDIRIM) H ON H.ID = I.ID

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT 
			'25',
			0,
			SUM(INDIRIMTUTARI) AS INDIRIMTUTARI,
			SUBSTRING(AREYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, SUM(AMIKTAR))+' ADET ALANA '+CONVERT(VARCHAR, SUM(VMIKTAR))+' ADET ÜRÜNDE '+CONVERT(VARCHAR, CAST(ROUND(SUM(INDIRIMTUTARI),2) AS MONEY),1)+' TL İNDİRİM',
			0
		FROM #INDIRIM
		WHERE SIRANO = 1
		GROUP BY AREYONADI

		DROP TABLE #FIS
		DROP TABLE #INDIRIM		
	END


	
	SELECT PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO FROM #RETTABLE
	
	DROP TABLE #REYONPROMOSYON
	DROP TABLE #RETTABLE
GO

ALTER PROCEDURE [dbo].[SP_BEKLETME_DETAY_INSERT]
	@ID				INT	= NULL,
	@FISID			INT,
	@SATIRNO		INT,
	@TIP			VARCHAR(3),
	@PLUNO			INT,
	@BARKOD			VARCHAR(20),
	@STOKKODU		VARCHAR(20),
	@STOKADI		VARCHAR(50),
	@KDV			FLOAT,
	@DEPARTMAN		INT,
	@MIKTAR			FLOAT,
	@BIRIM			VARCHAR(10),
	@FIYAT			FLOAT,
	@TUTAR			FLOAT,
	@INDYUZDE		FLOAT,
	@INDTUTAR		FLOAT,
	@ARTYUZDE		FLOAT,
	@ARTTUTAR		FLOAT,
	@KASIYERKODU	VARCHAR(4),
	@KASIYERADI		VARCHAR(20),
	@PLASIYERKODU	VARCHAR(4),
	@PLASIYERADI	VARCHAR(20),
	@ACIKLAMA		VARCHAR(MAX),
	@BARKODTYPE		TINYINT,
	@DOVIZKODU		VARCHAR(10),
	@DOVIZKURU		FLOAT,
	@DOVIZTUTARI	FLOAT,
	@PUAN			FLOAT,
	@TEVKIFATKODU	VARCHAR(10),
	@TEVKIFATACIKLAMA VARCHAR(100),
	@TEVKIFATORANI	INT,
	@OTVKODU	VARCHAR(10),
	@OTVACIKLAMA VARCHAR(100),
	@OTVORANI	INT
AS
	SET NOCOUNT ON
--SATIRNO OLUNCA HATA OLUYORDU YANLISLIKA UPDATE YAPIYORDU
--		SELECT @ID = ID FROM TBL_BEKLETME_DETAY WITH (NOLOCK)
--		WHERE FISID = @FISID AND SATIRNO = @SATIRNO
	IF ISNULL(@ID,0) > 0
		IF NOT EXISTS(SELECT TOP 1 ID FROM TBL_BEKLETME_DETAY WITH (NOLOCK) WHERE ID = @ID)
			SET @ID = NULL

	IF ISNULL(@ID,0) = 0
	BEGIN
		INSERT INTO TBL_BEKLETME_DETAY(FISID, SATIRNO, TIP, PLUNO, BARKOD, STOKKODU, STOKADI, KDV, DEPARTMAN, MIKTAR, BIRIM, FIYAT, TUTAR, INDYUZDE, INDTUTAR, ARTYUZDE, ARTTUTAR, KASIYERKODU, KASIYERADI, PLASIYERKODU, PLASIYERADI, ACIKLAMA, BARKODTYPE, DOVIZKODU, DOVIZKURU, DOVIZTUTARI, PUAN, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI)
		SELECT @FISID, @SATIRNO, @TIP, @PLUNO, @BARKOD, @STOKKODU, @STOKADI, @KDV, @DEPARTMAN, @MIKTAR, @BIRIM, @FIYAT, @TUTAR, @INDYUZDE, @INDTUTAR, @ARTYUZDE, @ARTTUTAR, @KASIYERKODU, @KASIYERADI, @PLASIYERKODU, @PLASIYERADI, @ACIKLAMA, @BARKODTYPE, @DOVIZKODU, @DOVIZKURU, @DOVIZTUTARI, @PUAN, @TEVKIFATKODU, @TEVKIFATACIKLAMA, @TEVKIFATORANI, @OTVKODU, @OTVACIKLAMA, @OTVORANI
		
		SELECT @ID = MAX(ID)
		FROM TBL_BEKLETME_DETAY WITH (NOLOCK)
		WHERE FISID = @FISID
	END
	ELSE
		UPDATE TBL_BEKLETME_DETAY
		SET
			TIP				= @TIP				,
			PLUNO			= @PLUNO			,
			BARKOD			= @BARKOD			,
			STOKKODU		= @STOKKODU			,
			STOKADI			= @STOKADI			,
			KDV				= @KDV				,
			DEPARTMAN		= @DEPARTMAN		,
			MIKTAR			= @MIKTAR			,
			BIRIM			= @BIRIM			,
			FIYAT			= @FIYAT			,
			TUTAR			= @TUTAR			,
			INDYUZDE		= @INDYUZDE			,
			INDTUTAR		= @INDTUTAR			,
			ARTYUZDE		= @ARTYUZDE			,
			ARTTUTAR		= @ARTTUTAR			,
			KASIYERKODU		= @KASIYERKODU		,
			KASIYERADI		= @KASIYERADI		,
			PLASIYERKODU	= @PLASIYERKODU		,
			PLASIYERADI		= @PLASIYERADI		,
			ACIKLAMA		= @ACIKLAMA			,
			BARKODTYPE		= @BARKODTYPE		,
			DOVIZKODU		= @DOVIZKODU		, 
			DOVIZKURU		= @DOVIZKURU		, 
			DOVIZTUTARI		= @DOVIZTUTARI		,
			PUAN			= @PUAN				,
			TEVKIFATKODU	= @TEVKIFATKODU		,
			TEVKIFATACIKLAMA= @TEVKIFATACIKLAMA	,
			TEVKIFATORANI	= @TEVKIFATORANI	,
			OTVKODU			= @OTVKODU			,
			OTVACIKLAMA		= @OTVACIKLAMA		,
			OTVORANI		= @OTVORANI			
		WHERE ID = @ID
	
	RETURN @ID
GO

ALTER PROCEDURE [dbo].[SP_PROMOSYON_TUTAR_KONTROL] 
	@CARITIPI		VARCHAR(1) ,
	@ARATOPLAM		FLOAT,
	@CARIKODU		VARCHAR(20) = NULL,
	@PUANPROMOSYON	BIT = NULL
AS

SET DATEFORMAT mdy; 


DECLARE @NOBONUSTUTAR FLOAT

SELECT @NOBONUSTUTAR = SUM(TUTAR) 
FROM TBL_BEKLETME_DETAY
WHERE FISID IN (
				SELECT ID FROM TBL_BEKLETME_MAIN
				WHERE ISBEKLETME = 0
				) AND
PLUNO IN (SELECT PLUNO FROM TBL_STOK_MAIN WHERE ISNULL(REYONADI,'') = 'NOBONUS'  OR (ISNULL(ISINDIRIM,1) = 0)) 

SET @NOBONUSTUTAR = ISNULL(@NOBONUSTUTAR,0)

SET @ARATOPLAM = @ARATOPLAM - @NOBONUSTUTAR

DECLARE @CARIGRUP VARCHAR(255)

IF ISNULL(@CARIKODU,'') <> ''
	SELECT @CARIGRUP = GRUP FROM TBL_CARI_MAIN WITH (NOLOCK)
	WHERE CARIKODU = @CARIKODU

SET @CARIGRUP = ISNULL(@CARIGRUP,'')

IF @CARITIPI = 'M' SET @CARITIPI = NULL

	
	DECLARE 
		@INDIRIMTIPI	VARCHAR(3),
		@INDYUZDE		FLOAT,
		@INDTUTAR		FLOAT,
		@PUAN			FLOAT
	
	CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PROMOSYONTIPI VARCHAR(3) COLLATE TURKISH_CI_AS, INDYUZDE FLOAT, INDTUTAR FLOAT, PUAN FLOAT, ACIKLAMA VARCHAR(MAX)  COLLATE TURKISH_CI_AS, PLUNO INT)
	
	IF @CARIGRUP = 'NOBONUS' 
	BEGIN
		SELECT * FROM #RETTABLE
	
		DROP TABLE #RETTABLE
		
		RETURN
	END
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA, PLUNO)
	SELECT  
		'15' AS INDIRIMTIPI,
		0,
		ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
		FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
		CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM',
		U.PLUNO
	FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.PLUNO 
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
	WHERE 
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P2' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
		(
			CARIGRUP = @CARIGRUP OR
			CARIGRUP = ''
		) AND
		VREYONADI = '' AND
		ISNULL(VPLUNO,0) = 0 AND 
		ISNULL(AMIKTAR,0) > 1  AND
		D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '15')
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA, PLUNO)
		SELECT  
			'15' AS INDIRIMTIPI,
			0,
			ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS INDTUTAR,
			FLOOR(D.MIKTAR / AMIKTAR) * PUAN,
			CONVERT(VARCHAR, FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR)+' ADET '+SUBSTRING(S.STOKADI,1,20)+' ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN FLOOR(D.MIKTAR / AMIKTAR) * INDTUTAR ELSE (((FLOOR(D.MIKTAR / AMIKTAR) * AMIKTAR) * (D.TUTAR / D.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM',
			U.PLUNO
		FROM TBL_PROMOSYON_URUN U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(D.MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.PLUNO 
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.PLUNO
		WHERE 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P2' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND 
			CARIGRUP = '' AND
			VREYONADI = '' AND
			ISNULL(VPLUNO,0) = 0 AND 
			ISNULL(AMIKTAR,0) > 1  AND
			D.MIKTAR >= ISNULL(AMIKTAR,0)
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
	SELECT  
		TOP 1
		CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
		0,
		CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
		CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
	WHERE 
		ARATOPLAM <= @ARATOPLAM AND 
		(
			CARIGRUP = @CARIGRUP OR
			CARIGRUP = ''
		) AND
		BASLANGICTARIHI <= GETDATE() AND
		BITISTARIHI >= GETDATE() AND
		PROMOSYONTIPI = 'P1' AND 
		CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
		PUAN = 0 AND
		ISNULL(PUANYUZDE,0) = 0
	ORDER BY ARATOPLAM DESC
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('05','07'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			CASE WHEN INDTUTAR > 0 THEN '07' ELSE '05' END ,
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			0,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			CARIGRUP = '' AND
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			PUAN = 0 AND
			ISNULL(PUANYUZDE,0) = 0
		ORDER BY ARATOPLAM DESC
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT  
		TOP 1
		'09',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * (INDTUTAR) ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2),
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
		ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * (INDTUTAR) ELSE 
		CASE WHEN U.VMIKTAR = 1 THEN (D.TOPTUTAR * INDYUZDE) / 100.00
		ELSE ((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
		END
		END,2)		
		 AS MONEY), 1)+' TL İND.',
		PUAN,
		U.VPLUNO
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT PLUNO, STOKADI, FIYAT FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, FIYAT) AS S ON S.PLUNO = U.VPLUNO
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 0
	ORDER BY U.ARATOPLAM DESC


	SELECT 
		STOKADI,
		ARATOPLAM,
		INDYUZDE,
		INDTUTAR,
		VMIKTAR,
		D.MIKTAR AS SATILANMIKTAR,
		D.TUTAR AS SATILANFIYAT,
		D.TOPTUTAR AS SATILANTUTAR,
		FLOOR(@ARATOPLAM / U.ARATOPLAM) AS KATSAYI,
		VPLUNO
	INTO #TEMP FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR, SUM(D.TUTAR) AS TOPTUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'P4' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			(U.INDTUTAR > 0) OR
			(U.INDYUZDE > 0)
		) AND
		U.TUMURUNLER = 1
	ORDER BY U.ARATOPLAM DESC
	

	DECLARE
		@STOKADI VARCHAR(50), 
		@ARATOP FLOAT, 
		@INDIRIM FLOAT, 
		@VMIKTAR FLOAT, 
		@SATILANMIKTAR FLOAT, 
		@SATILANFIYAT FLOAT, 
		@SATILANTUTAR FLOAT, 
		@KATSAYI INT,
		@TOPARA FLOAT,
		@VPLUNO INT

	DECLARE CURRT CURSOR FAST_FORWARD FOR
	SELECT ARATOPLAM FROM #TEMP
	GROUP BY ARATOPLAM
	OPEN CURRT

	FETCH NEXT FROM CURRT
	INTO @TOPARA

	WHILE @@FETCH_STATUS = 0
	BEGIN
		DECLARE CURR CURSOR FAST_FORWARD FOR
		SELECT STOKADI, ARATOPLAM, INDYUZDE, INDTUTAR, VMIKTAR, SATILANMIKTAR, SATILANFIYAT, SATILANTUTAR, KATSAYI, VPLUNO FROM #TEMP
		WHERE ARATOPLAM = @TOPARA AND SATILANMIKTAR >= VMIKTAR
		ORDER BY INDTUTAR DESC
		OPEN CURR

		FETCH NEXT FROM CURR
		INTO @STOKADI, @ARATOP, @INDYUZDE, @INDTUTAR, @VMIKTAR, @SATILANMIKTAR, @SATILANFIYAT, @SATILANTUTAR, @KATSAYI, @VPLUNO
	
		DECLARE @KALANKATSAYI INT

		SELECT TOP 1 @KALANKATSAYI = KATSAYI FROM #TEMP
		WHERE ARATOPLAM = @TOPARA

		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @KALANKATSAYI <= 0 BREAK
		
			SET @INDIRIM = 0

			IF @INDTUTAR > 0
			BEGIN
			
				IF @KALANKATSAYI >= @SATILANMIKTAR 
				BEGIN
					SET @INDIRIM = @SATILANMIKTAR  * @INDTUTAR
					SET @KALANKATSAYI = @KALANKATSAYI - @SATILANMIKTAR
				END
				ELSE
				BEGIN
					SET @INDIRIM = @KALANKATSAYI * @INDTUTAR
					SET @KALANKATSAYI = 0
					
				END
			END
			ELSE IF @INDYUZDE > 0
			BEGIN
				IF @KALANKATSAYI >= @SATILANMIKTAR
				BEGIN
					SET @INDIRIM = (@SATILANTUTAR * @INDYUZDE) / 100.00
					SET @KALANKATSAYI = @KALANKATSAYI - @SATILANMIKTAR
				END
				ELSE
				BEGIN
					SET @INDIRIM = ((@KALANKATSAYI * @SATILANFIYAT) * @INDYUZDE) / 100.00
					SET @KALANKATSAYI = 0
				END
			END

			IF @INDIRIM > 0
				INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
				SELECT 
					'09', 
					@INDYUZDE, 
					@INDIRIM, 
					CONVERT(VARCHAR, CAST(@ARATOP AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(@STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
					ROUND(@INDIRIM,2) AS MONEY), 1)+' TL İND.',
					0,
					@VPLUNO

			FETCH NEXT FROM CURR
			INTO @STOKADI, @ARATOP, @INDYUZDE, @INDTUTAR, @VMIKTAR, @SATILANMIKTAR, @SATILANFIYAT, @SATILANTUTAR, @KATSAYI, @VPLUNO
		END
	
		CLOSE CURR
		DEALLOCATE CURR

		FETCH NEXT FROM CURRT
		INTO @TOPARA
	END

	CLOSE CURRT
	DEALLOCATE CURRT

	DROP TABLE #TEMP
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('09'))
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT  
			TOP 1
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN,
			VPLUNO
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 0
		ORDER BY U.ARATOPLAM DESC

		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT  
			'09',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2),
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY) , 1)+' TL ALIŞVERİŞE '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(
			ROUND(CASE WHEN INDTUTAR > 0 THEN (CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * INDTUTAR ELSE 
			((((CASE WHEN FLOOR(@ARATOPLAM / U.ARATOPLAM) >= FLOOR(D.MIKTAR / U.VMIKTAR) THEN FLOOR(D.MIKTAR / U.VMIKTAR) ELSE FLOOR(@ARATOPLAM / U.ARATOPLAM) END) * D.TUTAR) * INDYUZDE) / 100.00) 
			END,2)		
			 AS MONEY), 1)+' TL İND.',
			PUAN,
			VPLUNO
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, MAX(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							GROUP BY PLUNO
							HAVING SUM(MIKTAR) > 0
						) AS D ON D.PLUNO = U.VPLUNO AND D.MIKTAR >= U.VMIKTAR
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = U.VPLUNO
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'P4' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				(U.INDTUTAR > 0) OR
				(U.INDYUZDE > 0)
			) AND
			U.TUMURUNLER = 1
		ORDER BY U.ARATOPLAM ASC
	
	END
	
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'10',
		U.INDYUZDE,
		CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END,
		CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ALIŞVERİŞİNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		(
			U.INDTUTAR > 0 OR
			U.INDYUZDE > 0
		)
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('10'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'10',
			U.INDYUZDE,
			CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END,
			CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY),1)+' TL '+SUBSTRING(U.VREYONADI,1,10)+'  REYONU ALIŞVERİŞİNE '+CONVERT(VARCHAR, CAST(CASE WHEN U.INDTUTAR > 0 THEN U.INDTUTAR ELSE (D.TUTAR * INDYUZDE) / 100.00 END AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR  FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			(
				U.INDTUTAR > 0 OR
				U.INDYUZDE > 0
			)
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT  
		'11',
		0,
		D.TUTAR,
		CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
		PUAN 
	FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI 
						HAVING SUM(MIKTAR) > 0
					) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
	WHERE 
		U.ARATOPLAM <= @ARATOPLAM AND 
		(
			U.CARIGRUP = @CARIGRUP OR
			U.CARIGRUP = ''
		) AND
		U.BASLANGICTARIHI <= GETDATE() AND
		U.BITISTARIHI >= GETDATE() AND
		U.PROMOSYONTIPI = 'PR' AND 
		U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
		U.INDTUTAR = 0 AND
		U.INDYUZDE = 0 
	ORDER BY U.ARATOPLAM DESC

	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('11'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
		SELECT  
			'11',
			0,
			D.TUTAR,
			CONVERT(VARCHAR, CAST(U.ARATOPLAM AS MONEY),1)+' TL ALIŞVERİŞE '+SUBSTRING(U.VREYONADI,1,10)+' REYONU ÜRÜNÜNE '+CONVERT(VARCHAR, CAST(D.TUTAR AS MONEY), 1)+' İND.',
			PUAN 
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			INNER JOIN (
							SELECT S.REYONADI, MIN(D.FIYAT) AS TUTAR FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
								INNER JOIN TBL_BEKLETME_MAIN AS M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
								INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.PLUNO = D.PLUNO
							GROUP BY S.REYONADI 
							HAVING SUM(MIKTAR) > 0
						) AS D ON U.VREYONADI COLLATE TURKISH_CI_AS  = D.REYONADI 
		WHERE 
			U.ARATOPLAM <= @ARATOPLAM AND 
			U.CARIGRUP = '' AND
			U.BASLANGICTARIHI <= GETDATE() AND
			U.BITISTARIHI >= GETDATE() AND
			U.PROMOSYONTIPI = 'PR' AND 
			U.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, U.CARITIPI) AND
			U.INDTUTAR = 0 AND
			U.INDYUZDE = 0 
		ORDER BY U.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
		0,
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
		CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN,
		A.PLUNO
	FROM (
			SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
			GROUP BY PLUNO
			HAVING SUM(MIKTAR) > 0
		) AS D 
		INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.PLUNO = D.PLUNO AND A.PLUNO = A.VPLUNO AND (A.CARIGRUP = @CARIGRUP OR A.CARIGRUP = '')
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = A.PLUNO
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
		(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0	AND
		A.VMIKTAR <> 0	
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI IN ('14','16'))
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
		SELECT 
			CASE WHEN A.INDTUTAR = 0 THEN '14' ELSE '16' END,
			0,
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END),
			CONVERT(VARCHAR, A.AMIKTAR)+' AD '+SUBSTRING(S.STOKADI,1,10)+' ALANA '+ CONVERT(VARCHAR, A.VMIKTAR)+' AD '+ CONVERT(VARCHAR, CAST((FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR <> 0 THEN A.INDTUTAR WHEN A.INDYUZDE <> 0 THEN (D.BIRIMFIYAT * A.INDYUZDE) / 100.00  ELSE D.BIRIMFIYAT END) AS MONEY),1)+' TL İND.',
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * PUAN,
			A.PLUNO
		FROM (
				SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT  
				FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
					INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				GROUP BY PLUNO
				HAVING SUM(MIKTAR) > 0
			) AS D 
			INNER JOIN TBL_PROMOSYON_URUN A WITH (NOLOCK) ON A.PLUNO = D.PLUNO AND A.PLUNO = A.VPLUNO AND A.CARIGRUP = ''
			INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = A.PLUNO
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI) AND
			(FLOOR(MIKTAR / (A.AMIKTAR + ISNULL(A.VMIKTAR,1))) * ISNULL(A.VMIKTAR,1)) * (CASE WHEN A.INDTUTAR = 0 THEN D.BIRIMFIYAT ELSE A.INDTUTAR END) <> 0 AND
			A.VMIKTAR <> 0	
	
	CREATE TABLE #PROMOSYONTBL(APLUNO INT, VPLUNO INT, VREYONADI VARCHAR(20)  COLLATE TURKISH_CI_AS, AMIKTAR FLOAT, VMIKTAR FLOAT, ALINANMIKTAR FLOAT, VERILENMIKTAR FLOAT, VERILENBIRIMFIYAT FLOAT, PUAN FLOAT, SATIR INT, INDYUZDE FLOAT, INDTUTAR FLOAT)		

	INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT PLUNO, VPLUNO, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		(
			A.CARIGRUP = @CARIGRUP OR
			A.CARIGRUP = ''
		) AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P3' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
		A.PLUNO <> A.VPLUNO 
	
	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 1)
		INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT PLUNO, VPLUNO, '', AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 1, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.CARIGRUP = '' AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P3' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.PLUNO <> A.VPLUNO 
		
	INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
	SELECT PLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
	FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
	WHERE 
		A.BASLANGICTARIHI <= GETDATE() AND
		A.BITISTARIHI >= GETDATE() AND
		A.PROMOSYONTIPI = 'P2' AND 
		A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
		(
			A.CARIGRUP = @CARIGRUP OR
			A.CARIGRUP = ''
		) AND
		ISNULL(VREYONADI,'') <> ''

	IF NOT EXISTS(SELECT TOP 1 1 FROM #PROMOSYONTBL WHERE SATIR = 2)
		INSERT INTO #PROMOSYONTBL(APLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, PUAN, SATIR, INDYUZDE, INDTUTAR)
		SELECT PLUNO, VPLUNO, VREYONADI, AMIKTAR, VMIKTAR, 0, 0, ISNULL(INDTUTAR,0), PUAN, 2, INDYUZDE, INDTUTAR
		FROM TBL_PROMOSYON_URUN A WITH (NOLOCK) 
		WHERE 
			A.BASLANGICTARIHI <= GETDATE() AND
			A.BITISTARIHI >= GETDATE() AND
			A.PROMOSYONTIPI = 'P2' AND 
			A.CARITIPI  COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, A.CARITIPI)  AND
			A.CARIGRUP = '' AND
			ISNULL(VREYONADI,'') <> ''

	UPDATE #PROMOSYONTBL
	SET	VPLUNO = H.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN TBL_STOK_MAIN S WITH (NOLOCK) ON S.REYONADI  COLLATE TURKISH_CI_AS = P.VREYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = S.PLUNO
	WHERE P.VREYONADI <> ''
	
	UPDATE #PROMOSYONTBL
	SET ALINANMIKTAR = H.MIKTAR
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = P.APLUNO

	UPDATE #PROMOSYONTBL
	SET VERILENMIKTAR = H.MIKTAR,
		VERILENBIRIMFIYAT = CASE WHEN VERILENBIRIMFIYAT > 0 THEN VERILENBIRIMFIYAT ELSE H.BIRIMFIYAT END
	FROM #PROMOSYONTBL P
		INNER JOIN (
						SELECT PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) H ON H.PLUNO = P.VPLUNO

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'18',
		0,
		(CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								((CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN VERILENMIKTAR * ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE INDTUTAR END)) 
								AS MONEY
							)		 
						,1)
		+' TL İND',
		FLOOR(ALINANMIKTAR / AMIKTAR) * PUAN,
		V.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS A ON A.PLUNO = P.APLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS V ON V.PLUNO = P.VPLUNO
	WHERE 
		VMIKTAR = 0 AND
		ALINANMIKTAR <> 0 AND 
		VERILENMIKTAR <> 0 AND
		FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, V.PLUNO, A.STOKADI, INDYUZDE, INDTUTAR  	
	
	DELETE FROM #PROMOSYONTBL
	WHERE VMIKTAR = 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'17',
		0,
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END), 
		CONVERT(VARCHAR, P.AMIKTAR)+' AD '+SUBSTRING(A.STOKADI,1,10)+' ALANA '+ SUBSTRING(V.STOKADI,1,10)+' ÜRÜNÜ '+
		CONVERT(VARCHAR,
						CAST(
								CASE 
									WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
										THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
										ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
									ELSE 0 
								END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END) AS MONEY
							)		 
						,1)
		+' TL İND',
		CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * PUAN,
		V.PLUNO
	FROM #PROMOSYONTBL P
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS A ON A.PLUNO = P.APLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS V ON V.PLUNO = P.VPLUNO
	WHERE ALINANMIKTAR <> 0 AND VERILENMIKTAR <> 0 AND
		(CASE 
			WHEN FLOOR(ALINANMIKTAR / AMIKTAR) > 0 
				THEN CASE WHEN FLOOR(ALINANMIKTAR / AMIKTAR) < FLOOR(VERILENMIKTAR / VMIKTAR) THEN FLOOR(ALINANMIKTAR / AMIKTAR) 
				ELSE FLOOR(VERILENMIKTAR / VMIKTAR) END 
			ELSE 0 
		END * (CASE WHEN ISNULL(INDYUZDE,0) > 0 THEN ROUND((VERILENBIRIMFIYAT * INDYUZDE) / 100.00,2) ELSE VERILENBIRIMFIYAT END)) <> 0
	GROUP BY ALINANMIKTAR, VERILENMIKTAR, VERILENBIRIMFIYAT, VMIKTAR, PUAN, P.AMIKTAR, V.STOKADI, A.STOKADI, INDYUZDE, V.PLUNO  	
		

	DROP TABLE #PROMOSYONTBL

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		--TOP 1 --MURAT
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND((T.TUTAR * INDYUZDE) / 100.00,2),
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN ÜRÜN ALANA '+CONVERT(VARCHAR, FLOOR(T.TUTAR / ARATOPLAM)*PUAN)+' PUAN HEDİYE',
		FLOOR(T.TUTAR / ARATOPLAM) * PUAN,
		NULL
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR > 0 AND
		ARATOPLAM > 0 AND 
		T.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR = 0 AND
		P.INDYUZDE = 0 AND 
		P.PUAN > 0
	ORDER BY P.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / CASE WHEN P.AMIKTAR = 0 THEN 1 ELSE P.AMIKTAR END)) ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR > 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR > 0
		
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND((H.TUTAR * INDYUZDE) / 100.00,2),
		SUBSTRING(P.REYONADI,1,10)+' RYN.DAN '+STOKADI+' ALANA '+CONVERT(VARCHAR, CAST(ROUND((H.TUTAR * INDYUZDE) / 100.00,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		H.PLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, S.PLUNO, S.STOKADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.PLUNO, S.STOKADI, S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) T ON T.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		T.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDYUZDE > 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		TOP 1
		CASE WHEN P.INDTUTAR > 0 THEN '24' ELSE '23' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.ARATOPLAM AS MONEY),1)+' TL ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  ELSE (H.TUTAR * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		AMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0 AND
		P.INDTUTAR > 0
	ORDER BY P.ARATOPLAM DESC

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
	SELECT 
		CASE WHEN P.INDTUTAR > 0 THEN '28' ELSE '29' END ,
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, FLOOR(H.MIKTAR / P.AMIKTAR) * P.AMIKTAR)+' ADET ALANA '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR  * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2) AS MONEY), 1)+' TL İND.',
		PUAN
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO = 0 AND 
		ARATOPLAM = 0 AND
		P.AMIKTAR > 0 AND
		P.VMIKTAR = 0 AND
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR * (FLOOR(H.MIKTAR / P.AMIKTAR)) ELSE (((FLOOR(H.MIKTAR / AMIKTAR) * AMIKTAR) * (H.TUTAR / H.MIKTAR)) * INDYUZDE) / 100.00 END,2) > 0 AND
		ISKADEMELI = 0
		

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 0 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(P.VMIKTAR * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((P.VMIKTAR*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
		(
			P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
			ISNULL(P.CARIGRUP,'') = ''
		) AND
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR = 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
	SELECT 
		'25',
		INDYUZDE,
		CASE WHEN P.VMIKTAR > L.MIKTAR THEN L.MIKTAR ELSE P.VMIKTAR END *
		ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2),
		SUBSTRING(P.REYONADI,1,10)+' REYONUNDAN '+CONVERT(VARCHAR, CAST(FLOOR(H.TUTAR / ARATOPLAM) * P.ARATOPLAM AS MONEY),1)+' TL ALANA '+SUBSTRING(S.STOKADI,1,10)+' '+CONVERT(VARCHAR, CAST(CASE WHEN P.VMIKTAR > L.MIKTAR THEN L.MIKTAR ELSE P.VMIKTAR END * ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE CASE WHEN INDYUZDE <> 0 THEN ((FLOOR(H.TUTAR / ARATOPLAM)*L.BIRIMFIYAT) * INDYUZDE) / 100  ELSE L.BIRIMFIYAT END END,2) AS MONEY), 1)+' TL İND.',
		PUAN,
		P.VPLUNO
	FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		INNER JOIN (
						SELECT PLUNO, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) / SUM(MIKTAR) AS BIRIMFIYAT, SUM(D.TUTAR - ABS(D.INDTUTAR) + D.ARTTUTAR) AS TUTAR, SUM(MIKTAR) AS MIKTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
						GROUP BY PLUNO
						HAVING SUM(MIKTAR) > 0
					) L ON L.PLUNO = P.VPLUNO
		INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS S ON S.PLUNO = L.PLUNO
	WHERE 
		P.BASLANGICTARIHI <= GETDATE() AND
		P.BITISTARIHI >= GETDATE() AND
		P.PROMOSYONTIPI = 'P7' AND 
		P.REYONADI <> '' AND 
		VPLUNO <> 0 AND 
		P.AMIKTAR = 0 AND
		P.VMIKTAR > 1 AND
		ARATOPLAM > 0 AND 
		H.TUTAR >= ARATOPLAM AND
		ISKADEMELI = 0

;WITH B AS (   -- Sepet satırları (reyon/fiyat/miktar)
    SELECT 
        D.FISID,
        S.REYONADI,
        D.PLUNO,
        CAST(D.MIKTAR AS DECIMAL(18,4)) AS MIKTAR,
        CAST(D.FIYAT  AS DECIMAL(18,4)) AS BIRIMFIYAT
    FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
    JOIN TBL_BEKLETME_MAIN  M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
    JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN WITH (NOLOCK) GROUP BY PLUNO, REYONADI) S ON S.PLUNO = D.PLUNO
    WHERE ISNULL(S.REYONADI,'') <> ''
),
P AS (   -- Aktif promosyonlar (P7 - Reyon bazlı)
    SELECT 
        P.* 
    FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
    WHERE 
        P.BASLANGICTARIHI <= GETDATE() AND
        P.BITISTARIHI     >= GETDATE() AND
        P.PROMOSYONTIPI   = 'P7' AND
        P.REYONADI        <> '' AND 
        P.AMIKTAR         <> 0 AND 
        P.VMIKTAR         <> 0 AND
        P.ISKADEMELI      = 0 AND
        P.ARATOPLAM       = 0 AND
        (
            (P.INDYUZDE <> 0) OR (P.INDTUTAR <> 0)
        ) AND
        P.CARITIPI COLLATE TURKISH_CI_AS = ISNULL(@CARITIPI, P.CARITIPI) AND
        (
            P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR ISNULL(P.CARIGRUP,'') = ''
        )
),
H AS (   -- Promosyona giren reyonların sepet toplamları ve bedava adet
    SELECT
        B.REYONADI,
        SUM(B.MIKTAR) AS TOPLAM_MIKTAR
    FROM B
    GROUP BY B.REYONADI
),
PX AS (  -- Sepete temas eden promosyon satırları
    SELECT 
        B.FISID, B.REYONADI, B.PLUNO, B.MIKTAR, B.BIRIMFIYAT,
        P.AMIKTAR, P.VMIKTAR, P.INDYUZDE, P.INDTUTAR, P.PUAN
    FROM B
    JOIN P ON B.REYONADI COLLATE TURKISH_CI_AS = P.REYONADI
),
G AS (   -- Reyon bazında hak edilen bedava adet (AMIKTAR & VMIKTAR P tablosundan)
    SELECT 
        PX.REYONADI,
        FLOOR(H.TOPLAM_MIKTAR / PX.AMIKTAR) * PX.VMIKTAR AS BEDAVA_ADET,
        MAX(PX.AMIKTAR)  AS AMIKTAR,   -- açıklama için
        MAX(PX.VMIKTAR)  AS VMIKTAR,   -- açıklama için
        MAX(PX.PUAN)     AS PUAN,      -- puan hesaplaması için
        MAX(PX.INDYUZDE) AS INDYUZDE,  -- tutar/indirim türü tespiti için
        MAX(PX.INDTUTAR) AS INDTUTAR
    FROM PX
    JOIN H ON H.REYONADI = PX.REYONADI
    GROUP BY PX.REYONADI, H.TOPLAM_MIKTAR, PX.AMIKTAR, PX.VMIKTAR
),
R AS (   -- Ucuzdan pahalıya kümülatif miktar (indirim dağıtımı için)
    SELECT
        PX.*,
        G.BEDAVA_ADET,
        SUM(PX.MIKTAR) OVER (
            PARTITION BY PX.REYONADI
            ORDER BY PX.BIRIMFIYAT ASC, PX.PLUNO
            ROWS UNBOUNDED PRECEDING
        ) AS CUM_QTY
    FROM PX
    JOIN G ON G.REYONADI = PX.REYONADI
),
F AS (   -- Satır başına indirimlenecek miktar
    SELECT
        R.REYONADI, R.PLUNO, R.MIKTAR, R.BIRIMFIYAT, 
        R.AMIKTAR, R.VMIKTAR, R.INDYUZDE, R.INDTUTAR, R.BEDAVA_ADET,
        (R.CUM_QTY - R.MIKTAR) AS PREV_QTY,
        CASE
            WHEN R.BEDAVA_ADET <= 0 THEN CAST(0 AS DECIMAL(18,4))
            WHEN (R.CUM_QTY - R.MIKTAR) >= R.BEDAVA_ADET THEN 0
            WHEN R.CUM_QTY <= R.BEDAVA_ADET THEN R.MIKTAR
            ELSE R.BEDAVA_ADET - (R.CUM_QTY - R.MIKTAR)
        END AS INDIRIM_ADEDI
    FROM R
),
T AS (   -- Satır başı indirim tutarı (yüzde ya da tutar bazlı)
    SELECT
        F.REYONADI,
        F.PLUNO,
        F.BIRIMFIYAT,
        F.INDIRIM_ADEDI,
        CASE 
            WHEN F.INDYUZDE > 0 
                THEN F.INDIRIM_ADEDI * F.BIRIMFIYAT * (F.INDYUZDE / 100.0)
            ELSE F.INDIRIM_ADEDI * F.INDTUTAR
        END AS INDIRIM_TUTARI
    FROM F
    WHERE F.INDIRIM_ADEDI > 0
),
SUMRY AS ( -- Reyon bazında toplam indirim, metin ve puan
    SELECT
        G.REYONADI,
        CAST(SUM(T.INDIRIM_TUTARI) AS DECIMAL(18,2)) AS TOPLAM_INDIRIM,
        -- Açıklama: "REYONUNDAN X ADET ALANA Y TL İND."
        SUBSTRING(G.REYONADI,1,10) + ' REYONUNDAN ' +
        CONVERT(VARCHAR, (FLOOR((SELECT SUM(MIKTAR) FROM B WHERE B.REYONADI=G.REYONADI) / G.AMIKTAR) * G.AMIKTAR)) +
        ' ADET ALANA ' +
        CONVERT(VARCHAR, CAST(SUM(T.INDIRIM_TUTARI) AS MONEY), 1) + ' TL İND.' AS ACIKLAMA,
        (G.BEDAVA_ADET * G.PUAN) AS PUAN_TOPLAM
    FROM G
    LEFT JOIN T ON T.REYONADI = G.REYONADI
    GROUP BY G.REYONADI, G.AMIKTAR, G.BEDAVA_ADET, G.PUAN
)
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN)
SELECT
    '25'                    AS KOD,         -- mevcut yapınızdaki sabit alan
    0                       AS FLAG,        -- mevcut yapınızdaki sabit alan
    S.TOPLAM_INDIRIM        AS INDIRIM_TUTARI,
    S.ACIKLAMA              AS ACIKLAMA,
    S.PUAN_TOPLAM           AS PUAN
FROM SUMRY S
WHERE S.TOPLAM_INDIRIM > 0
ORDER BY S.REYONADI;
		 
	--R1 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R1 @CARITIPI, @CARIGRUP

	--R2 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R2 @CARITIPI, @CARIGRUP

	--R3 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R3 @CARITIPI, @CARIGRUP

	--R4 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R4 @CARITIPI, @CARIGRUP

	--R5 PROMOSYONU ÜRÜN PROMOSYONU OLARAK ALINMIŞTIR

	--R6 PROMOSYONU
	INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE , INDTUTAR , PUAN , ACIKLAMA , PLUNO)
	EXEC SP_REYON_PROMOSYON_R6 @CARITIPI, @CARIGRUP, @ARATOPLAM

	IF EXISTS(
				SELECT TOP 1 1 FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
				INNER JOIN (
								SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
								FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
									INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
									INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
								GROUP BY S.REYONADI
							) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
				WHERE 
					P.BASLANGICTARIHI <= GETDATE() AND
					P.BITISTARIHI >= GETDATE() AND
					P.PROMOSYONTIPI = 'P7' AND 
					P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
					(
						P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
						ISNULL(P.CARIGRUP,'') = ''
					) AND
					P.REYONADI <> '' AND 
					VPLUNO = 0 AND 
					H.TUTAR >= ARATOPLAM AND
					ISKADEMELI = 1
			)
	BEGIN
		DECLARE @REYONADI		VARCHAR(20),
				@REYONINDYUZDE	FLOAT,
				@REYONINDTUTAR	FLOAT,
				@STOKPLUNO		INT,
				@STOKMIKTAR		FLOAT,
				@STOKFIYAT		FLOAT,
				@ADET			FLOAT
				
		
		CREATE TABLE #STABLE(ID INT IDENTITY(1,1) PRIMARY KEY, PLUNO INT, FIYAT FLOAT, INDTUTAR FLOAT, SIRANO INT)

		DECLARE CURREYON CURSOR FAST_FORWARD FOR
		SELECT P.REYONADI, P.INDYUZDE, P.INDTUTAR FROM TBL_PROMOSYON_REYON P WITH (NOLOCK)
		INNER JOIN (
						SELECT S.REYONADI, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) AS TUTAR
						FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
							INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
							INNER JOIN (SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, REYONADI) AS S ON S.PLUNO = D.PLUNO
						GROUP BY S.REYONADI
					) H ON H.REYONADI  COLLATE TURKISH_CI_AS= P.REYONADI
		WHERE 
			P.BASLANGICTARIHI <= GETDATE() AND
			P.BITISTARIHI >= GETDATE() AND
			P.PROMOSYONTIPI = 'P7' AND 
			P.CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, P.CARITIPI)  AND
			(
				P.CARIGRUP = ISNULL(@CARIGRUP, P.CARIGRUP) OR
				ISNULL(P.CARIGRUP,'') = ''
			) AND
			P.REYONADI <> '' AND 
			VPLUNO = 0 AND 
			H.TUTAR >= ARATOPLAM AND
			ISKADEMELI = 1
		OPEN CURREYON
		
		FETCH NEXT FROM CURREYON
		INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		
		WHILE @@FETCH_STATUS = 0
		BEGIN
			DELETE FROM #STABLE	
			
			DECLARE CURRSTOK CURSOR FAST_FORWARD FOR
			SELECT D.PLUNO, SUM(MIKTAR) AS MIKTAR, SUM(D.TUTAR) / SUM(MIKTAR) AS FIYAT
			FROM TBL_BEKLETME_DETAY D WITH (NOLOCK)
				INNER JOIN TBL_BEKLETME_MAIN M WITH (NOLOCK) ON M.ID = D.FISID AND M.ISBEKLETME = 0
				INNER JOIN (SELECT PLUNO, STOKADI, REYONADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI, REYONADI) AS S ON S.PLUNO = D.PLUNO
			WHERE S.REYONADI = @REYONADI 
			GROUP BY D.PLUNO
			HAVING (SUM(MIKTAR) <> 0) AND (SUM(MIKTAR) - FLOOR(SUM(MIKTAR)) = 0)
			OPEN CURRSTOK
			
			FETCH NEXT FROM CURRSTOK
			INTO @STOKPLUNO, @STOKMIKTAR, @STOKFIYAT
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @ADET = @STOKMIKTAR
				
				WHILE @ADET > 0 
				BEGIN
					INSERT INTO #STABLE(PLUNO, FIYAT, INDTUTAR, SIRANO)
					SELECT @STOKPLUNO, @STOKFIYAT, CASE WHEN @REYONINDYUZDE = 0 THEN @REYONINDTUTAR ELSE ROUND((@STOKFIYAT * @REYONINDYUZDE) / 100.00,2) END, 0
					
					SET @ADET = @ADET - 1
				END
			
				FETCH NEXT FROM CURRSTOK
				INTO @STOKPLUNO, @STOKMIKTAR, @STOKFIYAT
			END
			
			CLOSE CURRSTOK
			DEALLOCATE CURRSTOK
			
			UPDATE #STABLE
			SET SIRANO = H.SIRANO
			FROM #STABLE S
				INNER JOIN (SELECT ID, ROW_NUMBER() OVER(ORDER BY FIYAT DESC) AS SIRANO FROM #STABLE) AS H ON H.ID = S.ID
			
			DELETE FROM #STABLE 
			WHERE SIRANO % 2 <> 0

			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, ACIKLAMA, PUAN, PLUNO)
			SELECT 
				'30',
				@REYONINDYUZDE,
				ROUND(INDTUTAR,2),
				SUBSTRING(M.STOKADI,1,20)+' KADEMELİ '+CONVERT(VARCHAR, CAST(INDTUTAR AS MONEY), 1)+' TL İND.',
				0,
				M.PLUNO
			FROM #STABLE S
				INNER JOIN (SELECT PLUNO, STOKADI FROM TBL_STOK_MAIN S WITH (NOLOCK) GROUP BY PLUNO, STOKADI) AS M ON M.PLUNO = S.PLUNO
			WHERE INDTUTAR <> 0
			ORDER BY INDTUTAR DESC
			
			FETCH NEXT FROM CURREYON
			INTO @REYONADI, @REYONINDYUZDE, @REYONINDTUTAR
		END
		
		CLOSE CURREYON
		DEALLOCATE CURREYON		
		
		DROP TABLE #STABLE
	END
	
	DECLARE @TOPLAMINDIRIM FLOAT
	
	SELECT @TOPLAMINDIRIM  = SUM(INDTUTAR) FROM #RETTABLE
	
	SET @ARATOPLAM = @ARATOPLAM - ABS(ISNULL(@TOPLAMINDIRIM,0))
	
	IF @ARATOPLAM > 0
	BEGIN
		INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
		SELECT  
			TOP 1
			'27',
			INDYUZDE,
			ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
			CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
				CASE 
					WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
					ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
				END
			END,
			CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
			CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
				CONVERT(VARCHAR, 
						CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
							CASE 
								WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
								ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
							END
						END				
				)+' PUAN'
			ELSE
				CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
			END
		FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
		WHERE 
			ARATOPLAM <= @ARATOPLAM AND 
			BASLANGICTARIHI <= GETDATE() AND
			BITISTARIHI >= GETDATE() AND
			PROMOSYONTIPI = 'P1' AND 
			CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
			(
				CARIGRUP = @CARIGRUP OR
				CARIGRUP = ''
			) AND
			(
				PUAN > 0 OR
				ISNULL(PUANYUZDE,0) > 0
			) AND
			INDYUZDE = 0 AND
			INDTUTAR = 0
		ORDER BY ARATOPLAM DESC
		
		IF NOT EXISTS(SELECT TOP 1 1 FROM #RETTABLE WHERE PROMOSYONTIPI = '27')
			INSERT INTO #RETTABLE(PROMOSYONTIPI, INDYUZDE, INDTUTAR, PUAN, ACIKLAMA)
			SELECT  
				TOP 1
				'27',
				INDYUZDE,
				ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2),
				CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
					CASE 
						WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
						ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
					END
				END,
				CONVERT(VARCHAR, CAST(ROUND(@ARATOPLAM,2) AS MONEY),1)+' TL ALIŞ VERİŞE '+
				CASE WHEN ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) = 0 THEN
					CONVERT(VARCHAR, 
						CASE WHEN ARATOPLAM <= 0 THEN 0 ELSE 
							CASE 
								WHEN ISNULL(PUANYUZDE,0) > 0 THEN ROUND((@ARATOPLAM * PUANYUZDE) / 100.00,2)
								ELSE FLOOR(@ARATOPLAM / ARATOPLAM) * PUAN 
							END
						END)+' PUAN'
				ELSE
					CONVERT(VARCHAR, CAST(ROUND(CASE WHEN INDTUTAR > 0 THEN INDTUTAR ELSE (@ARATOPLAM * INDYUZDE) / 100.00 END,2) AS MONEY),1)+' İNDİRİM'
				END
			FROM TBL_PROMOSYON_TUTAR U WITH (NOLOCK)
			WHERE 
				ARATOPLAM <= @ARATOPLAM AND 
				BASLANGICTARIHI <= GETDATE() AND
				BITISTARIHI >= GETDATE() AND
				PROMOSYONTIPI = 'P1' AND 
				CARITIPI  COLLATE TURKISH_CI_AS= ISNULL(@CARITIPI, CARITIPI) AND
				CARIGRUP = '' AND
				(
					PUAN > 0 OR
					ISNULL(PUANYUZDE,0) > 0
				) AND
				INDYUZDE = 0 AND
				INDTUTAR = 0
			ORDER BY ARATOPLAM DESC
	END

	IF ISNULL(@PUANPROMOSYON,0) = 1 
	BEGIN
		IF EXISTS(SELECT * FROM #RETTABLE WHERE INDTUTAR > 0)
			UPDATE #RETTABLE
			SET PUAN = 0

		DELETE FROM #RETTABLE
		WHERE INDTUTAR <= 0 AND PUAN <= 0
	END

	SELECT * FROM #RETTABLE
	
	DROP TABLE #RETTABLE
GO

ALTER PROCEDURE [dbo].[SP_XZ_REPORT]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL
AS


DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPPOSKREDITOPLAMI FLOAT	 ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPFISNO IS NOT NULL
BEGIN
	DECLARE @TEKRARFISID INT, @ONCEKIFISNO INT
	
	SELECT @TMPSONTARIH = TARIH, @TMPPOSKREDITOPLAMI = ISNULL(POSKREDITOPLAMI,0)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE FISNO = @TMPFISNO AND TIP = @TMPTIP
	
	SELECT @ONCEKIFISNO = MAX(CONVERT(INT, FISNO))
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT, FISNO) < CONVERT(INT, @TMPFISNO) AND TIP = @TMPTIP
	
	SELECT @TMPILKTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT,FISNO) = @ONCEKIFISNO AND TIP = @TMPTIP
	
	IF @TMPILKTARIH IS NULL SET @TMPILKTARIH = GETDATE() - 365
END
ELSE
BEGIN
	IF @TMPTARIH IS NULL 
		SELECT TOP 1 @TMPTARIH = MAX(TARIH)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z'
	--	ORDER BY TARIH DESC
		
		SELECT TOP 1 @TMPPOSKREDITOPLAMI = ISNULL(POSKREDITOPLAMI,0)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = @TMPTIP
		ORDER BY TARIH DESC
	
	IF @TMPFISNO IS NULL
		SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = @TMPTIP
	--	ORDER BY TARIH DESC

	SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
	SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

	IF @TMPILKTARIH IS NULL
		SET @TMPILKTARIH = @TMPTARIH
	IF @TMPSONTARIH IS NULL
		SET @TMPSONTARIH = GETDATE()
END

SET @TMPPOSKREDITOPLAMI = ISNULL(@TMPPOSKREDITOPLAMI,0)




SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT, KREDINO INT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DÖKÜMÜ' ELSE 'FİŞ DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DÖKÜMÜ' ELSE 'FATURA DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İRSALİYE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'BELGE İPTALLERİ ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPKDV, KDVHRC, TOPLAM, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CASE 
		WHEN ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'') <> '' THEN
		ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'')
	ELSE 'KSM'+CONVERT(VARCHAR, D.DEPARTMAN)+' (%'+CONVERT(VARCHAR, D.KDV)+' KDV)' END AS ACIKLAMA,
	SUM((CASE WHEN D.BELGETIPI = 2 THEN -1 ELSE 1 END) * D.NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL D
WHERE D.BELGETIPI IN(0,1,2,8)
GROUP BY D.DEPARTMAN, D.KDV
ORDER BY D.DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET TAHSİLAT DÖKÜMÜ(SATIŞ-İADE)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3,
	KREDINO
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI, KREDINO
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'[99]-PUAN',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3,
	99
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'

UPDATE #RETTABLE
SET TUTAR = TUTAR + K.INDTUTAR
FROM #RETTABLE R
	INNER JOIN (
					SELECT ISNULL(KREDINO,0) AS KREDINO, ABS(SUM(INDTUTAR)) AS INDTUTAR
					FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
					WHERE FISID IN (
										SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
										WHERE 
											F.KASANO = @TMPKASANO AND 
											F.TARIH >= @TMPILKTARIH AND 
											F.TARIH <= @TMPSONTARIH AND 
											F.TIP IN (0,1,8) AND 
											F.INDTUTAR <> 0
									) AND
					ISNULL(KREDINO,0) > 0 
					GROUP BY ISNULL(KREDINO,0)
				) AS K ON K.KREDINO = R.KREDINO
WHERE TIP = 3

DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-TAHSİLAT TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-SATIŞ TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'BRÜT TAHSİLAT DÖKÜMÜ(SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(ABS(D.TUTAR)) AS TUTAR,
	11,
	KREDINO
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI, KREDINO
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'[99]-PUAN',
	SUM(ABS(D.INDTUTAR)) AS TUTAR,
	11,
	99
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,8) AND
	D.PROMOSYONTIPI = '99'

UPDATE #RETTABLE
SET TUTAR = TUTAR + K.INDTUTAR
FROM #RETTABLE R
	INNER JOIN (
					SELECT ISNULL(KREDINO,0) AS KREDINO, ABS(SUM(INDTUTAR)) AS INDTUTAR
					FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
					WHERE FISID IN (
										SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
										WHERE 
											F.KASANO = @TMPKASANO AND 
											F.TARIH >= @TMPILKTARIH AND 
											F.TARIH <= @TMPSONTARIH AND 
											F.TIP IN (0,1,8) AND 
											F.INDTUTAR <> 0
									) AND
					ISNULL(KREDINO,0) > 0 
					GROUP BY ISNULL(KREDINO,0)
				) AS K ON K.KREDINO = R.KREDINO
WHERE TIP = 11

DECLARE @TMPBRUTAHSILATTOPLAMI DECIMAL(21,6), @TMPBRUTODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPBRUTAHSILATTOPLAMI = SUM(TUTAR) 
FROM #RETTABLE
WHERE TIP = 11
 
SELECT @TMPBRUTODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-BRÜT TAHSİLAT TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0),
	11

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-BRÜT SATIŞ TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0), --+ ISNULL(ABS(@TMPBRUTODEMETIPIINDIRIMI),0),
	11


IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA GİRİŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA ÇIKIŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İND.TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'ARA TOPLAM İND. ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS ADET 
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME TİPİ İND. ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ABS(SUM(INDTUTAR)) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PUAN HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS ADET FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'VER.HED.ÇEK TOP.['+CONVERT(VARCHAR, ISNULL(COUNT(ID),0))+']',
	SUM(ABS(TUTAR)) AS TUTAR,
	6
FROM TBL_HEDIYE_CEK HC WITH (NOLOCK) 
WHERE TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA GİRİŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA ÇIKIŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #NAKITODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
WHERE KREDINO = 0
GROUP BY FISID

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #ODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
GROUP BY FISID

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET NAKİT TOPLAMI',
	SUM(
		(CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0)
		-(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS NAKITTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT JOIN #NAKITODEME D ON  D.FISID=M.ID 
WHERE M.TIP<> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET CİRO',
	SUM(
		((CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0))-
		(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0) AS CIROTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT OUTER JOIN #ODEME D ON  D.FISID=M.ID 
WHERE M.TIP <> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

DROP TABLE #NAKITODEME
DROP TABLE #ODEME

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'YEMEK ÇEKİ HARİÇ KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF DEĞERLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF KDV', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF TOPLAM', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPPOSKREDITOPLAMI AS POSKREDITOPLAMI, @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
GO

ALTER PROCEDURE [dbo].[SP_HAREKET_LIST]
	@TIP	VARCHAR(2) = NULL, --HR, HD, HI
	@KASANO	INT = NULL,
	@TARIH	SMALLDATETIME = NULL,
	@INTERFORMAT	BIT = NULL,
	@REMOVEBARPOSFORMATS BIT = NULL,
	@ISMAXMIKTAR	BIT = NULL
AS
	SET DATEFORMAT mdy; 

	IF  @TIP IS NULL
	BEGIN
		SET @TIP = 'HR'
		SET @KASANO = 1
		SET @TARIH = '01/09/2026'
		SET @REMOVEBARPOSFORMATS = 0
		SET @INTERFORMAT = 0
		SET @ISMAXMIKTAR=1
	END

DECLARE
	@AY		INT,
	@YIL	INT,
	@GUN	INT

SELECT
	@GUN	= DATEPART(DD, @TARIH),
	@AY		= DATEPART(MM, @TARIH),
	@YIL	= DATEPART(YY, @TARIH)

CREATE TABLE #HRTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, BELGEID INT, TIP INT, SATIRNO INT, PLASIYERKODU VARCHAR(4), DATA VARCHAR(MAX), TARIH DATETIME, TOPLAM FLOAT, CARIKODU VARCHAR(20), TIPNO INT, YETKILIKODU VARCHAR(4), YETKILIADI VARCHAR(20), EFATURAKODU VARCHAR(20), UUID VARCHAR(50), ISEFATURA BIT, ISPUAN BIT)
IF @TIP = 'TO'
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, ISPUAN)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 6 THEN 'T,N,00,'
				WHEN 7 THEN 'O,N,00,'
			END+
			dbo.SR(CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END,20)+','+
			dbo.SR(BELGEKODU,20)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1,
		0
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		TIP IN (6, 7)

	SELECT DATA FROM #HRTABLE
END
ELSE
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, YETKILIKODU, YETKILIADI, EFATURAKODU, UUID, ISEFATURA, ISPUAN)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 0 THEN '01,FIS'
				WHEN 1 THEN '02,FAT'
				WHEN 8 THEN '46,IRS'
				WHEN 2 THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 1 THEN '24,GPS' ELSE '21,FAT' END
			ELSE '01,FIS' END+','+
			dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+'     '+
			dbo.ZL(KASIYERKODU,4)+','+
			dbo.ZL(CONVERT(VARCHAR,BELGEKODU),6)+'  '+
			dbo.ZL(CONVERT(VARCHAR,KASIYERKODU),4),
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1, 
		YETKILIKODU, 
		YETKILIADI,
		EFATURAKODU,
		UUID,
		ISEFATURA,
		0
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		(
		((@TIP = 'HR') AND (TIP IN (0, 1, 8))) OR
		(((@TIP = 'HD') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 0)) OR
		(((@TIP = 'HR') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 1)) OR
		((@TIP = 'HI') AND (TIP IN (3)))
		)


	CREATE TABLE #DETAY(ID INT, PLUNO INT, BARKOD VARCHAR(20), ISDELETE BIT)

	INSERT INTO #DETAY(ID, PLUNO, BARKOD, ISDELETE)
	SELECT ID, PLUNO, BARKOD, 0
	FROM TBL_FIS_DETAY D
	WHERE D.FISID IN (SELECT ID FROM #HRTABLE)

	UPDATE #DETAY
	SET ISDELETE = 1
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN S ON S.BARKOD = D.BARKOD

	DELETE FROM #DETAY	WHERE ISDELETE = 1

	UPDATE #DETAY SET ISDELETE = 1

	UPDATE #DETAY
	SET BARKOD = M.BARKOD,
		ISDELETE = 0
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN M ON M.PLUNO = D.PLUNO

	DELETE FROM #DETAY WHERE ISDELETE = 1

	UPDATE TBL_FIS_DETAY
	SET BARKOD = D.BARKOD
	FROM TBL_FIS_DETAY F WITH (NOLOCK)
		INNER JOIN #DETAY D ON D.ID = F.ID

	DROP TABLE #DETAY

	SELECT FISID
	INTO #ODEME FROM TBL_FIS_ODEME
	WHERE 
		FISID IN (SELECT BELGEID FROM #HRTABLE) AND 
		KREDINO = 39
	GROUP BY FISID

	UPDATE #HRTABLE
	SET ISPUAN = 1
	FROM #HRTABLE H
		INNER JOIN TBL_FIS_PROMOSYON P WITH (NOLOCK) ON P.FISID = H.BELGEID AND P.PROMOSYONTIPI = '99'
		INNER JOIN TBL_FIS_ODEME O WITH (NOLOCK) ON O.FISID = H.BELGEID AND O.TUTAR = 0.01

	IF @TIP = 'HR'
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, ISPUAN)
		SELECT
			ID,
			TIP,
			9999999,
				CASE TIP
					WHEN 4 THEN '13,KGR'
				ELSE '12,KCK' END+',000000'+
				dbo.ZL(CONVERT(VARCHAR,BELGEKODU),4)+'00,'+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
			TARIH,
			TUTAR,
			CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
			1,
			0
		FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE
			KASANO = @KASANO AND
			DATEPART(DD, TARIH) = @GUN AND
			DATEPART(MM, TARIH) = @AY AND
			DATEPART(YY, TARIH) = @YIL AND
			TIP IN (4, 5)
	END

	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		TIP,
		2,
		'03,TAR,'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(DD, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(MM, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(YY, TARIH)),4)+'  ,'+
		dbo.SR(LEFT(CONVERT(VARCHAR, TARIH, 114),8),12),
		2
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
	SELECT
		D.FISID,
		MIN(SATIRNO)+2,
			CASE D.TIP
				WHEN 'SAT' THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN CASE WHEN M.TIP = 2 THEN '05' ELSE '04' END ELSE CASE WHEN M.TIP = 2 THEN '25' ELSE '04' END END
				WHEN 'IPT' THEN '05'
			ELSE '04' END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN D.TIP ELSE CASE WHEN M.TIP = 2 THEN CASE WHEN D.TIP = 'SAT' THEN 'GAL' ELSE 'IPT' END ELSE D.TIP END END+','+
			dbo.ZL(CONVERT(VARCHAR, 
									CASE 
										WHEN ABS(SUM(MIKTAR)) < 99.999 THEN CONVERT(DECIMAL(5,3), ROUND(ABS(SUM(MIKTAR)),3,1)) 
										WHEN ABS(SUM(MIKTAR)) < 999.99 THEN CONVERT(DECIMAL(5,2), ROUND(ABS(SUM(MIKTAR)),2,1)) 
										WHEN ABS(SUM(MIKTAR)) < 9999.9 THEN CONVERT(DECIMAL(5,1), ROUND(ABS(SUM(MIKTAR)),1,1)) 
										WHEN ABS(SUM(MIKTAR)) < 99999 THEN CONVERT(DECIMAL(5,0), ROUND(ABS(SUM(MIKTAR)),0,1)) 
									ELSE CONVERT(DECIMAL(5,3), ABS(SUM(MIKTAR))) END),6)+
			dbo.ZL(CONVERT(VARCHAR,PLUNO),6)+','+
			dbo.ZL(CONVERT(VARCHAR,DEPARTMAN),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(SUM(D.TUTAR)))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(SUM(D.TUTAR)) AS money), 0),10) END,
			D.PLASIYERKODU,
			3
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND D.TIP IN ('SAT', 'IPT')
	GROUP BY D.FISID, M.TIP, D.TIP, D.PLUNO, D.BARKOD, D.DEPARTMAN, D.PLASIYERKODU 
	ORDER BY D.FISID, MIN(SATIRNO)

	IF (ISNULL(@INTERFORMAT,0) = 1)
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
		SELECT
			D.FISID,
			MIN(SATIRNO)+2,
				'38,BKD,'+
				dbo.SR(SUBSTRING(BARKOD,1,12),12)+','+dbo.SR(SUBSTRING(BARKOD,13,8),12),
				D.PLASIYERKODU,
				4
		FROM TBL_FIS_DETAY D WITH (NOLOCK)
		WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT', 'IPT')
		GROUP BY D.FISID, D.TIP, D.BARKOD, D.PLASIYERKODU
		ORDER BY D.FISID


		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> '' AND TIPNO = 3
	END
	ELSE
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> ''  AND TIPNO = 3


	SELECT MIN(ID) AS ID, D.FISID, D.PLUNO, MIN(SATIRNO) AS SATIRNO, CONVERT(VARCHAR(10), '') AS KASIYERKODU
	INTO #FISDETAY FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') 
	GROUP BY D.FISID, D.PLUNO
	ORDER BY D.FISID, MIN(SATIRNO)
	
	UPDATE  #FISDETAY
	SET KASIYERKODU = D.KASIYERKODU
	FROM #FISDETAY F
		INNER JOIN TBL_FIS_DETAY D WITH (NOLOCK) ON D.ID = F.ID

	SELECT FISID, ISNULL(PLUNO,0) AS PLUNO, SUM(INDTUTAR) AS INDTUTAR INTO #PROMOSYON FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
	WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
	GROUP BY FISID, ISNULL(PLUNO,0)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		D.SATIRNO+2,
			'06'+',IND,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			6
	FROM #FISDETAY D
		INNER JOIN #PROMOSYON P ON P.FISID = D.FISID AND P.PLUNO = D.PLUNO

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		SATIRNO+2,
			'39'+',ART,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		7
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') AND ARTTUTAR <> 0
	ORDER BY D.FISID, D.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'06'+',IND,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			8
	FROM TBL_FIS_MAIN F WITH (NOLOCK)
		INNER JOIN #PROMOSYON P ON P.FISID = F.ID AND P.PLUNO = 0
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND P.INDTUTAR <> 0
	ORDER BY ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'39'+',ART,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		8
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND ARTTUTAR <> 0
	ORDER BY ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			10001,
				'53'+',PRM,'+ dbo.ZL(P.PROMOSYONTIPI,2)+'    '+CASE WHEN ISNULL(PLUNO,0) > 0 THEN dbo.ZL(CONVERT(VARCHAR, PLUNO),6) ELSE '    '+CASE WHEN KREDINO > 0 THEN dbo.ZL(CONVERT(VARCHAR,KREDINO),2) ELSE '  ' END END+','+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			9
		FROM TBL_FIS_PROMOSYON P WITH (NOLOCK)
			INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = P.FISID
		WHERE P.FISID IN (SELECT BELGEID FROM #HRTABLE) 
		ORDER BY P.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		20001,
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN '08,TOP,            ,'
		ELSE CASE WHEN TIP = 3 THEN '30,FIP,           0,' ELSE '08,TOP,            ,' END END
		+
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),MAX(ABS(TOPLAM)))*100,0))),12)
		ELSE dbo.SL(CONVERT(VARCHAR, CAST(MAX(ABS(TOPLAM)) AS money), 0),12) END,
		10
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)
	GROUP BY BELGEID, TIP

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		O.FISID,
		2000001+O.ID,
		CASE WHEN H.ISPUAN = 1 AND TUTAR = 0.01 THEN
			'10,KRD,          99,'+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),0)*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(0 AS money), 0),12) END
		ELSE
			CASE KREDINO
				WHEN 0 THEN '09,NAK,            ,'
			ELSE '10,KRD,          '+dbo.ZL(CONVERT(VARCHAR, O.KREDINO),2)+',' END+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(O.TUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(O.TUTAR) AS money), 0),12) END
		END,
		11
	FROM TBL_FIS_ODEME O WITH (NOLOCK)
		INNER JOIN (SELECT BELGEID, ISPUAN FROM #HRTABLE WHERE SATIRNO = 1) AS H ON H.BELGEID = O.FISID
	ORDER BY O.FISID, O.ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT 
			H.BELGEID,
			A.SATIRNO,
			'77,ONY,'+
			dbo.SR(YETKILIKODU,4)+dbo.SR(SUBSTRING(YETKILIADI,1,8),8)+','+
			dbo.SR(SUBSTRING(YETKILIADI,9,12),12),
			12
		FROM #HRTABLE H
			INNER JOIN (
						SELECT
							BELGEID,
							MAX(SATIRNO)+1 AS SATIRNO
						FROM #HRTABLE
						GROUP BY BELGEID
					   ) AS A ON A.BELGEID = H.BELGEID
		WHERE ISNULL(YETKILIKODU,'') <> ''
	
	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'44,'+CASE WHEN ISNULL(ISEFATURA,0) = 1 THEN 'EFK' ELSE 'EAK' END+','+ 
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5) AND ISNULL(EFATURAKODU,'') <> ''
		GROUP BY BELGEID, ISNULL(ISEFATURA,0), ISNULL(EFATURAKODU,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'55,'+'UI1'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+2,
			'55,'+'UI2'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),21,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),33,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			3000001+K.ID,
			'77,'+'KDV'+','+ 
			dbo.ZL(CONVERT(VARCHAR, KDV),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVTUTAR))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVTUTAR) AS money), 0),10) END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVHARICTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVHARICTUTAR) AS money), 0),12) END,
			12
		FROM TBL_FIS_KDV K WITH (NOLOCK)
		WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
		ORDER BY FISID, KDV

	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		H.BELGEID,
		MAX(H.SATIRNO)+1,
		'11,SON,'+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),1,12),12)+','+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),13,8),8)+'   '+CASE WHEN O.FISID IS NULL THEN ' ' ELSE 'A' END,
		13
	FROM #HRTABLE H
		LEFT JOIN #ODEME O ON O.FISID = H.BELGEID
	WHERE ISNULL(H.TIP,0) NOT IN (4,5,10)
	GROUP BY H.BELGEID, ISNULL(H.CARIKODU,''), O.FISID

	IF @REMOVEBARPOSFORMATS = 0
		IF @TIP = 'HR'
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA,TIPNO)
		SELECT
			9999999+ID,
			9999999+ID,
			'16,ZRP,'+
			dbo.SR(CONVERT(VARCHAR, @TARIH, 103),12)+','+
			dbo.SR(SUBSTRING(CONVERT(VARCHAR, TARIH, 114),1,8),12),
			14
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z' AND TARIH >= @TARIH AND TARIH < @TARIH+1

	SELECT '1,'+dbo.ZL(CONVERT(VARCHAR, ROW_NUMBER() OVER(ORDER BY BELGEID, SATIRNO, TIPNO, DATA)),5)+ ',' + DATA AS DATA FROM #HRTABLE

	DROP TABLE #FISDETAY
	DROP TABLE #PROMOSYON
	DROP TABLE #ODEME
END


DROP TABLE #HRTABLE
GO

ALTER PROCEDURE [dbo].[SP_HAREKET_LIST]
	@TIP	VARCHAR(2) = NULL, --HR, HD, HI
	@KASANO	INT = NULL,
	@TARIH	SMALLDATETIME = NULL,
	@INTERFORMAT	BIT = NULL,
	@REMOVEBARPOSFORMATS BIT = NULL,
	@ISMAXMIKTAR	BIT = NULL
AS
	SET DATEFORMAT mdy; 

	IF  @TIP IS NULL
	BEGIN
		SET @TIP = 'HR'
		SET @KASANO = 7
		SET @TARIH = '02/11/2026'
		SET @REMOVEBARPOSFORMATS = 0
		SET @INTERFORMAT = 0
		SET @ISMAXMIKTAR=1
	END

DECLARE
	@AY		INT,
	@YIL	INT,
	@GUN	INT

SELECT
	@GUN	= DATEPART(DD, @TARIH),
	@AY		= DATEPART(MM, @TARIH),
	@YIL	= DATEPART(YY, @TARIH)

CREATE TABLE #HRTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, BELGEID INT, TIP INT, SATIRNO INT, PLASIYERKODU VARCHAR(4), DATA VARCHAR(MAX), TARIH DATETIME, TOPLAM FLOAT, CARIKODU VARCHAR(20), TIPNO INT, YETKILIKODU VARCHAR(4), YETKILIADI VARCHAR(20), EFATURAKODU VARCHAR(20), UUID VARCHAR(50), ISEFATURA BIT, ISPUAN BIT)
IF @TIP = 'TO'
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, ISPUAN)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 6 THEN 'T,N,00,'
				WHEN 7 THEN 'O,N,00,'
			END+
			dbo.SR(CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END,20)+','+
			dbo.SR(BELGEKODU,20)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1,
		0
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		TIP IN (6, 7)

	SELECT DATA FROM #HRTABLE
END
ELSE
BEGIN
	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, YETKILIKODU, YETKILIADI, EFATURAKODU, UUID, ISEFATURA, ISPUAN)
	SELECT
		ID,
		TIP,
		1,
			CASE TIP
				WHEN 0 THEN '01,FIS'
				WHEN 1 THEN '02,FAT'
				WHEN 8 THEN '46,IRS'
				WHEN 2 THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 1 THEN '24,GPS' ELSE '21,FAT' END
			ELSE '01,FIS' END+','+
			dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+'     '+
			dbo.ZL(KASIYERKODU,4)+','+
			dbo.ZL(CONVERT(VARCHAR,BELGEKODU),6)+'  '+
			dbo.ZL(CONVERT(VARCHAR,KASIYERKODU),4),
		TARIH,
		TUTAR,
		CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
		1, 
		YETKILIKODU, 
		YETKILIADI,
		EFATURAKODU,
		UUID,
		ISEFATURA,
		0
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE
		KASANO = @KASANO AND
		DATEPART(DD, TARIH) = @GUN AND
		DATEPART(MM, TARIH) = @AY AND
		DATEPART(YY, TARIH) = @YIL AND
		(
		((@TIP = 'HR') AND (TIP IN (0, 1, 8))) OR
		(((@TIP = 'HD') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 0)) OR
		(((@TIP = 'HR') AND (TIP IN (2))) AND (ISNULL(@INTERFORMAT,0) = 1)) OR
		((@TIP = 'HI') AND (TIP IN (3)))
		)


	CREATE TABLE #DETAY(ID INT, PLUNO INT, BARKOD VARCHAR(20), ISDELETE BIT)

	INSERT INTO #DETAY(ID, PLUNO, BARKOD, ISDELETE)
	SELECT ID, PLUNO, BARKOD, 0
	FROM TBL_FIS_DETAY D
	WHERE D.FISID IN (SELECT ID FROM #HRTABLE)

	UPDATE #DETAY
	SET ISDELETE = 1
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN S ON S.BARKOD = D.BARKOD

	DELETE FROM #DETAY	WHERE ISDELETE = 1

	UPDATE #DETAY SET ISDELETE = 1

	UPDATE #DETAY
	SET BARKOD = M.BARKOD,
		ISDELETE = 0
	FROM #DETAY D
		INNER JOIN TBL_STOK_MAIN M ON M.PLUNO = D.PLUNO

	DELETE FROM #DETAY WHERE ISDELETE = 1

	UPDATE TBL_FIS_DETAY
	SET BARKOD = D.BARKOD
	FROM TBL_FIS_DETAY F WITH (NOLOCK)
		INNER JOIN #DETAY D ON D.ID = F.ID

	DROP TABLE #DETAY

	SELECT FISID
	INTO #ODEME FROM TBL_FIS_ODEME
	WHERE 
		FISID IN (SELECT BELGEID FROM #HRTABLE) AND 
		KREDINO = 39
	GROUP BY FISID

	UPDATE #HRTABLE
	SET ISPUAN = 1
	FROM #HRTABLE H
		INNER JOIN TBL_FIS_PROMOSYON P WITH (NOLOCK) ON P.FISID = H.BELGEID AND P.PROMOSYONTIPI = '99'
		INNER JOIN TBL_FIS_ODEME O WITH (NOLOCK) ON O.FISID = H.BELGEID AND O.TUTAR = 0.01

	IF @TIP = 'HR'
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TARIH, TOPLAM, CARIKODU, TIPNO, ISPUAN)
		SELECT
			ID,
			TIP,
			9999999,
				CASE TIP
					WHEN 4 THEN '13,KGR'
				ELSE '12,KCK' END+',000000'+
				dbo.ZL(CONVERT(VARCHAR,BELGEKODU),4)+'00,'+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(TUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(TUTAR) AS money), 0),12) END,
			TARIH,
			TUTAR,
			CASE WHEN CARIKODU = NULL OR CARIKODU='' THEN VERGINO ELSE CARIKODU END AS CARIKODU,
			1,
			0
		FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE
			KASANO = @KASANO AND
			DATEPART(DD, TARIH) = @GUN AND
			DATEPART(MM, TARIH) = @AY AND
			DATEPART(YY, TARIH) = @YIL AND
			TIP IN (4, 5)
	END

	INSERT INTO #HRTABLE(BELGEID, TIP, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		TIP,
		2,
		'03,TAR,'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(DD, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(MM, TARIH)),2)+'/'+
		dbo.ZL(CONVERT(VARCHAR, DATEPART(YY, TARIH)),4)+'  ,'+
		dbo.SR(LEFT(CONVERT(VARCHAR, TARIH, 114),8),12),
		2
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
	SELECT
		D.FISID,
		MIN(SATIRNO)+2,
			CASE D.TIP
				WHEN 'SAT' THEN CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN CASE WHEN M.TIP = 2 THEN '05' ELSE '04' END ELSE CASE WHEN M.TIP = 2 THEN '25' ELSE '04' END END
				WHEN 'IPT' THEN '05'
			ELSE '04' END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN D.TIP ELSE CASE WHEN M.TIP = 2 THEN CASE WHEN D.TIP = 'SAT' THEN 'GAL' ELSE 'IPT' END ELSE D.TIP END END+','+
			dbo.ZL(CONVERT(VARCHAR,CASE
				WHEN ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))) < 100     THEN CONVERT(VARCHAR(32), CONVERT(DECIMAL(5,3), ROUND(ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))), 3)))
				WHEN ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))) < 1000    THEN CONVERT(VARCHAR(32), CONVERT(DECIMAL(5,2), ROUND(ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))), 2)))
				WHEN ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))) < 10000   THEN CONVERT(VARCHAR(32), CONVERT(DECIMAL(5,1), ROUND(ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))), 1)))
				WHEN ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))) < 100000  THEN CONVERT(VARCHAR(32), CONVERT(DECIMAL(5,0), ROUND(ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))), 0)))
				ELSE CONVERT(VARCHAR(32), CONVERT(DECIMAL(18,3), ROUND(ABS(CONVERT(DECIMAL(18,6), SUM(MIKTAR))), 3)))  -- dışarı taşarsa
			END) ,6)+
			dbo.ZL(CONVERT(VARCHAR,PLUNO),6)+','+
			dbo.ZL(CONVERT(VARCHAR,DEPARTMAN),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(SUM(D.TUTAR)))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(SUM(D.TUTAR)) AS money), 0),10) END,
			D.PLASIYERKODU,
			3
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
		INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND D.TIP IN ('SAT', 'IPT')
	GROUP BY D.FISID, M.TIP, D.TIP, D.PLUNO, D.BARKOD, D.DEPARTMAN, D.PLASIYERKODU 
	ORDER BY D.FISID, MIN(SATIRNO)

	IF (ISNULL(@INTERFORMAT,0) = 1)
	BEGIN
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, PLASIYERKODU, TIPNO)
		SELECT
			D.FISID,
			MIN(SATIRNO)+2,
				'38,BKD,'+
				dbo.SR(SUBSTRING(BARKOD,1,12),12)+','+dbo.SR(SUBSTRING(BARKOD,13,8),12),
				D.PLASIYERKODU,
				4
		FROM TBL_FIS_DETAY D WITH (NOLOCK)
		WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT', 'IPT')
		GROUP BY D.FISID, D.TIP, D.BARKOD, D.PLASIYERKODU
		ORDER BY D.FISID


		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> '' AND TIPNO = 3
	END
	ELSE
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			SATIRNO,
			'20,STC,'+dbo.ZL(CONVERT(VARCHAR,@KASANO),3)+ '     ' + dbo.ZL(PLASIYERKODU,4)+',            ',
			5
		FROM #HRTABLE
		WHERE ISNULL(PLASIYERKODU,'') <> ''  AND TIPNO = 3


	SELECT MIN(ID) AS ID, D.FISID, D.PLUNO, MIN(SATIRNO) AS SATIRNO, CONVERT(VARCHAR(10), '') AS KASIYERKODU
	INTO #FISDETAY FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') 
	GROUP BY D.FISID, D.PLUNO
	ORDER BY D.FISID, MIN(SATIRNO)
	
	UPDATE  #FISDETAY
	SET KASIYERKODU = D.KASIYERKODU
	FROM #FISDETAY F
		INNER JOIN TBL_FIS_DETAY D WITH (NOLOCK) ON D.ID = F.ID

	SELECT FISID, ISNULL(PLUNO,0) AS PLUNO, SUM(INDTUTAR) AS INDTUTAR INTO #PROMOSYON FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
	WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
	GROUP BY FISID, ISNULL(PLUNO,0)

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		D.SATIRNO+2,
			'06'+',IND,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			6
	FROM #FISDETAY D
		INNER JOIN #PROMOSYON P ON P.FISID = D.FISID AND P.PLUNO = D.PLUNO

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		D.FISID,
		SATIRNO+2,
			'39'+',ART,SNS '+
			dbo.ZL(CONVERT(VARCHAR,D.KASIYERKODU),4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		7
	FROM TBL_FIS_DETAY D WITH (NOLOCK)
	WHERE D.FISID IN (SELECT BELGEID FROM #HRTABLE) AND TIP IN ('SAT') AND ARTTUTAR <> 0
	ORDER BY D.FISID, D.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'06'+',IND,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,0))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			8
	FROM TBL_FIS_MAIN F WITH (NOLOCK)
		INNER JOIN #PROMOSYON P ON P.FISID = F.ID AND P.PLUNO = 0
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND P.INDTUTAR <> 0
	ORDER BY ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		ID,
		10000,
			'39'+',ART,TOP '+
			dbo.ZL(KASIYERKODU,4)+' '+
			'%'+
			dbo.ZL(CONVERT(VARCHAR, ABS(CONVERT(INT,ARTYUZDE))),2)+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(ARTTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(ARTTUTAR) AS money), 0),12) END,
		8
	FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE ID IN (SELECT BELGEID FROM #HRTABLE) AND ARTTUTAR <> 0
	ORDER BY ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			10001,
				'53'+',PRM,'+ dbo.ZL(P.PROMOSYONTIPI,2)+'    '+CASE WHEN ISNULL(PLUNO,0) > 0 THEN dbo.ZL(CONVERT(VARCHAR, PLUNO),6) ELSE '    '+CASE WHEN KREDINO > 0 THEN dbo.ZL(CONVERT(VARCHAR,KREDINO),2) ELSE '  ' END END+','+
				CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(P.INDTUTAR))*100,0))),12)
				ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(P.INDTUTAR) AS money), 0),12) END,
			9
		FROM TBL_FIS_PROMOSYON P WITH (NOLOCK)
			INNER JOIN TBL_FIS_MAIN F WITH (NOLOCK) ON F.ID = P.FISID
		WHERE P.FISID IN (SELECT BELGEID FROM #HRTABLE) 
		ORDER BY P.ID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		BELGEID,
		20001,
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN '08,TOP,            ,'
		ELSE CASE WHEN TIP = 3 THEN '30,FIP,           0,' ELSE '08,TOP,            ,' END END
		+
		CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),MAX(ABS(TOPLAM)))*100,0))),12)
		ELSE dbo.SL(CONVERT(VARCHAR, CAST(MAX(ABS(TOPLAM)) AS money), 0),12) END,
		10
	FROM #HRTABLE
	WHERE TIP NOT IN (4,5)
	GROUP BY BELGEID, TIP

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		O.FISID,
		2000001+O.ID,
		CASE WHEN H.ISPUAN = 1 AND TUTAR = 0.01 THEN
			'10,KRD,          99,'+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),0)*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(0 AS money), 0),12) END
		ELSE
			CASE KREDINO
				WHEN 0 THEN '09,NAK,            ,'
			ELSE '10,KRD,          '+dbo.ZL(CONVERT(VARCHAR, O.KREDINO),2)+',' END+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(O.TUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(O.TUTAR) AS money), 0),12) END
		END,
		11
	FROM TBL_FIS_ODEME O WITH (NOLOCK)
		INNER JOIN (SELECT BELGEID, ISPUAN FROM #HRTABLE WHERE SATIRNO = 1) AS H ON H.BELGEID = O.FISID
	ORDER BY O.FISID, O.ID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT 
			H.BELGEID,
			A.SATIRNO,
			'77,ONY,'+
			dbo.SR(YETKILIKODU,4)+dbo.SR(SUBSTRING(YETKILIADI,1,8),8)+','+
			dbo.SR(SUBSTRING(YETKILIADI,9,12),12),
			12
		FROM #HRTABLE H
			INNER JOIN (
						SELECT
							BELGEID,
							MAX(SATIRNO)+1 AS SATIRNO
						FROM #HRTABLE
						GROUP BY BELGEID
					   ) AS A ON A.BELGEID = H.BELGEID
		WHERE ISNULL(YETKILIKODU,'') <> ''
	
	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'44,'+CASE WHEN ISNULL(ISEFATURA,0) = 1 THEN 'EFK' ELSE 'EAK' END+','+ 
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(EFATURAKODU,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5) AND ISNULL(EFATURAKODU,'') <> ''
		GROUP BY BELGEID, ISNULL(ISEFATURA,0), ISNULL(EFATURAKODU,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+1,
			'55,'+'UI1'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),1,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),13,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			BELGEID,
			MAX(SATIRNO)+2,
			'55,'+'UI2'+','+ 
			dbo.SR(SUBSTRING(ISNULL(UUID,''),21,12),12)+','+
			dbo.SR(SUBSTRING(ISNULL(UUID,''),33,8),12),
			10
		FROM #HRTABLE
		WHERE ISNULL(TIP,0) NOT IN (4,5,10) AND ISNULL(UUID,'') <> ''
		GROUP BY BELGEID, ISNULL(UUID,'')

	IF @REMOVEBARPOSFORMATS = 0
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
		SELECT
			FISID,
			3000001+K.ID,
			'77,'+'KDV'+','+ 
			dbo.ZL(CONVERT(VARCHAR, KDV),2)+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVTUTAR))*100,0))),10)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVTUTAR) AS money), 0),10) END+','+
			CASE WHEN ISNULL(@INTERFORMAT,0) = 0 THEN dbo.SL(CONVERT(VARCHAR, CONVERT(BIGINT, ROUND(CONVERT(DECIMAL(10,2),ABS(KDVHARICTUTAR))*100,0))),12)
			ELSE dbo.SL(CONVERT(VARCHAR, CAST(ABS(KDVHARICTUTAR) AS money), 0),12) END,
			12
		FROM TBL_FIS_KDV K WITH (NOLOCK)
		WHERE FISID IN (SELECT BELGEID FROM #HRTABLE)
		ORDER BY FISID, KDV

	UPDATE #HRTABLE
	SET CARIKODU = A.CARIKODU,
		EFATURAKODU = A.EFATURAKODU,
		ISEFATURA = A.ISEFATURA,
		UUID = A.UUID
	FROM #HRTABLE H
		INNER JOIN (SELECT BELGEID, CARIKODU, EFATURAKODU, UUID, ISEFATURA FROM #HRTABLE WHERE SATIRNO = 1) A ON A.BELGEID = H.BELGEID

	INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA, TIPNO)
	SELECT
		H.BELGEID,
		MAX(H.SATIRNO)+1,
		'11,SON,'+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),1,12),12)+','+
		dbo.SR(SUBSTRING(ISNULL(H.CARIKODU,''),13,8),8)+'   '+CASE WHEN O.FISID IS NULL THEN ' ' ELSE 'A' END,
		13
	FROM #HRTABLE H
		LEFT JOIN #ODEME O ON O.FISID = H.BELGEID
	WHERE ISNULL(H.TIP,0) NOT IN (4,5,10)
	GROUP BY H.BELGEID, ISNULL(H.CARIKODU,''), O.FISID

	IF @REMOVEBARPOSFORMATS = 0
		IF @TIP = 'HR'
		INSERT INTO #HRTABLE(BELGEID, SATIRNO, DATA,TIPNO)
		SELECT
			9999999+ID,
			9999999+ID,
			'16,ZRP,'+
			dbo.SR(CONVERT(VARCHAR, @TARIH, 103),12)+','+
			dbo.SR(SUBSTRING(CONVERT(VARCHAR, TARIH, 114),1,8),12),
			14
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z' AND TARIH >= @TARIH AND TARIH < @TARIH+1

	SELECT '1,'+dbo.ZL(CONVERT(VARCHAR, ROW_NUMBER() OVER(ORDER BY BELGEID, SATIRNO, TIPNO, DATA)),5)+ ',' + DATA AS DATA FROM #HRTABLE

	DROP TABLE #FISDETAY
	DROP TABLE #PROMOSYON
	DROP TABLE #ODEME
END


DROP TABLE #HRTABLE
GO

ALTER PROCEDURE [dbo].[SP_XZ_REPORT]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL
AS


DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPPOSKREDITOPLAMI FLOAT	 ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPFISNO IS NOT NULL
BEGIN
	DECLARE @TEKRARFISID INT, @ONCEKIFISNO INT
	
	SELECT @TMPSONTARIH = TARIH, @TMPPOSKREDITOPLAMI = ISNULL(POSKREDITOPLAMI,0)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE FISNO = @TMPFISNO AND TIP = @TMPTIP
	
	SELECT @ONCEKIFISNO = MAX(CONVERT(INT, FISNO))
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT, FISNO) < CONVERT(INT, @TMPFISNO) AND TIP = @TMPTIP
	
	SELECT @TMPILKTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT,FISNO) = @ONCEKIFISNO AND TIP = @TMPTIP
	
	IF @TMPILKTARIH IS NULL SET @TMPILKTARIH = GETDATE() - 365
END
ELSE
BEGIN
	IF @TMPTARIH IS NULL 
		SELECT TOP 1 @TMPTARIH = MAX(TARIH)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = 'Z'
	--	ORDER BY TARIH DESC
		
		SELECT TOP 1 @TMPPOSKREDITOPLAMI = ISNULL(POSKREDITOPLAMI,0)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = @TMPTIP
		ORDER BY TARIH DESC
	
	IF @TMPFISNO IS NULL
		SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
		FROM TBL_XZ_LOG WITH (NOLOCK)
		WHERE TIP = @TMPTIP
	--	ORDER BY TARIH DESC

	SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
	SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

	IF @TMPILKTARIH IS NULL
		SET @TMPILKTARIH = @TMPTARIH
	IF @TMPSONTARIH IS NULL
		SET @TMPSONTARIH = GETDATE()
END

SET @TMPPOSKREDITOPLAMI = ISNULL(@TMPPOSKREDITOPLAMI,0)




SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT, KREDINO INT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM TBL_FIS_DETAY D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DÖKÜMÜ' ELSE 'FİŞ DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM TBL_FIS_MAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DÖKÜMÜ' ELSE 'FATURA DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İRSALİYE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'BELGE İPTALLERİ ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPKDV, KDVHRC, TOPLAM, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CASE 
		WHEN ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'') <> '' THEN
		ISNULL((SELECT TOP 1 DEPARTMANADI FROM TBL_DEPARTMAN WITH (NOLOCK) WHERE DEPARTMAN = D.DEPARTMAN),'')
	ELSE 'KSM'+CONVERT(VARCHAR, D.DEPARTMAN)+' (%'+CONVERT(VARCHAR, D.KDV)+' KDV)' END AS ACIKLAMA,
	SUM((CASE WHEN D.BELGETIPI = 2 THEN -1 ELSE 1 END) * D.NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL D
WHERE D.BELGETIPI IN(0,1,2,8)
GROUP BY D.DEPARTMAN, D.KDV
ORDER BY D.DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET TAHSİLAT DÖKÜMÜ(SATIŞ-İADE)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3,
	KREDINO
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI, KREDINO
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'[99]-PUAN',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3,
	99
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'[87]-A.V.CEKI',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3,
	87
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '87'

UPDATE #RETTABLE
SET TUTAR = TUTAR + K.INDTUTAR
FROM #RETTABLE R
	INNER JOIN (
					SELECT ISNULL(KREDINO,0) AS KREDINO, ABS(SUM(INDTUTAR)) AS INDTUTAR
					FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
					WHERE FISID IN (
										SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
										WHERE 
											F.KASANO = @TMPKASANO AND 
											F.TARIH >= @TMPILKTARIH AND 
											F.TARIH <= @TMPSONTARIH AND 
											F.TIP IN (0,1,8) AND 
											F.INDTUTAR <> 0
									) AND
					ISNULL(KREDINO,0) > 0 
					GROUP BY ISNULL(KREDINO,0)
				) AS K ON K.KREDINO = R.KREDINO
WHERE TIP = 3

DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-TAHSİLAT TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-SATIŞ TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'BRÜT TAHSİLAT DÖKÜMÜ(SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+ D.KREDITIPI,
	SUM(ABS(D.TUTAR)) AS TUTAR,
	11,
	KREDINO
FROM TBL_FIS_ODEME D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI, KREDINO
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+']-'+D.KREDITIPI

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'[99]-PUAN',
	SUM(ABS(D.INDTUTAR)) AS TUTAR,
	11,
	99
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,8) AND
	D.PROMOSYONTIPI = '99'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP, KREDINO)
SELECT
	'[87]-A.V.CEKI',
	SUM(ABS(D.INDTUTAR)) AS TUTAR,
	11,
	87
FROM TBL_FIS_PROMOSYON D WITH (NOLOCK)
	INNER JOIN TBL_FIS_MAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,8) AND
	D.PROMOSYONTIPI = '87'

UPDATE #RETTABLE
SET TUTAR = TUTAR + K.INDTUTAR
FROM #RETTABLE R
	INNER JOIN (
					SELECT ISNULL(KREDINO,0) AS KREDINO, ABS(SUM(INDTUTAR)) AS INDTUTAR
					FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
					WHERE FISID IN (
										SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
										WHERE 
											F.KASANO = @TMPKASANO AND 
											F.TARIH >= @TMPILKTARIH AND 
											F.TARIH <= @TMPSONTARIH AND 
											F.TIP IN (0,1,8) AND 
											F.INDTUTAR <> 0
									) AND
					ISNULL(KREDINO,0) > 0 
					GROUP BY ISNULL(KREDINO,0)
				) AS K ON K.KREDINO = R.KREDINO
WHERE TIP = 11

DECLARE @TMPBRUTAHSILATTOPLAMI DECIMAL(21,6), @TMPBRUTODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPBRUTAHSILATTOPLAMI = SUM(TUTAR) 
FROM #RETTABLE
WHERE TIP = 11
 
SELECT @TMPBRUTODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998]-BRÜT TAHSİLAT TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0),
	11

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999]-BRÜT SATIŞ TOPLAMI',
	ISNULL(@TMPBRUTAHSILATTOPLAMI,0), --+ ISNULL(ABS(@TMPBRUTODEMETIPIINDIRIMI),0),
	11


IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA GİRİŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM TBL_FIS_MAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA ÇIKIŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İND.TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'ARA TOPLAM İND. ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS ADET 
		FROM TBL_FIS_MAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM TBL_FIS_PROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME TİPİ İND. ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ABS(SUM(INDTUTAR)) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PUAN HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'A.V.CEKI HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM TBL_FIS_PROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM TBL_FIS_MAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 87 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS ADET FROM TBL_FIS_MAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'VER.HED.ÇEK TOP.['+CONVERT(VARCHAR, ISNULL(COUNT(ID),0))+']',
	SUM(ABS(TUTAR)) AS TUTAR,
	6
FROM TBL_HEDIYE_CEK HC WITH (NOLOCK) 
WHERE TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA GİRİŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA ÇIKIŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #NAKITODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
WHERE KREDINO = 0
GROUP BY FISID

SELECT FISID, SUM(ABS(TUTAR)) AS TUTAR INTO #ODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
GROUP BY FISID

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET NAKİT TOPLAMI',
	SUM(
		(CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0)
		-(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) AS NAKITTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT JOIN #NAKITODEME D ON  D.FISID=M.ID 
WHERE M.TIP<> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'NET CİRO',
	SUM(
		((CASE WHEN M.TIP = 2 THEN -1 ELSE 1 END) * ISNULL(D.TUTAR,0))-
		(CASE WHEN M.TIP IN (5,7) THEN 1 WHEN M.TIP IN (4,6) THEN -1 ELSE 0 END) * ABS(M.TUTAR)
		) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0) AS CIROTOPLAM,
	3
FROM TBL_FIS_MAIN M WITH (NOLOCK) 
	LEFT OUTER JOIN #ODEME D ON  D.FISID=M.ID 
WHERE M.TIP <> '3' AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <=@TMPSONTARIH

DROP TABLE #NAKITODEME
DROP TABLE #ODEME

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '-------------------------', 0, 1
--MURAT
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'YEMEK ÇEKİ HARİÇ KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM TBL_FIS_ODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF DEĞERLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF KDV', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF TOPLAM', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPPOSKREDITOPLAMI AS POSKREDITOPLAMI, @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
GO
ALTER PROCEDURE [dbo].[SP_XZ_REPORT_EARCHIVE]
	@TIP		VARCHAR(1) = 'Z',
	@KASANO		INT = 1,
	@KASIYERKODU VARCHAR(10) = '0001',
	@KASIYERADI	VARCHAR(50) = 'OLCAY DAĞLI',
	@ILKTARIH	DATETIME = NULL,
	@SONTARIH	DATETIME = NULL,
	@FISNO		VARCHAR(20) = NULL,
	@TARIH		DATETIME =NULL,
	@NORMALMODE	BIT = NULL
AS


DECLARE
	@TMPTIP			VARCHAR(1)	 ,
	@TMPKASANO		INT			 ,
	@TMPKASIYERKODU VARCHAR(10)  ,
	@TMPKASIYERADI	VARCHAR(50)  ,
	@TMPILKTARIH	DATETIME	 ,
	@TMPSONTARIH	DATETIME	 ,
	@TMPFISNO		VARCHAR(20)  ,
	@TMPTARIH		DATETIME	 

SET	@TMPTIP			=  @TIP		
SET	@TMPKASANO		=  @KASANO		
SET	@TMPKASIYERKODU	=  @KASIYERKODU
SET	@TMPKASIYERADI	=  @KASIYERADI	
SET	@TMPILKTARIH	=  @ILKTARIH	
SET	@TMPSONTARIH	=  @SONTARIH	
SET	@TMPFISNO		=  @FISNO		
SET	@TMPTARIH		=  @TARIH		

DECLARE @TMPKUMULATIFTUTAR FLOAT, @TMPKUMULATIFKDV FLOAT

IF @TMPTARIH IS NULL 
	SELECT TOP 1 @TMPTARIH = MAX(TARIH)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = 'Z'
--	ORDER BY TARIH DESC

IF @TMPFISNO IS NULL
	SELECT TOP 1 @TMPFISNO = dbo.ZL(CONVERT(VARCHAR, MAX(CONVERT(INT, FISNO)) + 1),6)
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE TIP = @TMPTIP
--	ORDER BY TARIH DESC

SET @TMPTARIH = ISNULL(@TMPTARIH, GETDATE()-365)
SET @TMPFISNO = ISNULL(@TMPFISNO, '000001')

IF @TMPILKTARIH IS NULL
	SET @TMPILKTARIH = @TMPTARIH
IF @TMPSONTARIH IS NULL
	SET @TMPSONTARIH = GETDATE()


IF @TMPFISNO IS NOT NULL
BEGIN
	DECLARE @TEKRARFISID INT, @ONCEKIFISNO INT
	
	SELECT @TMPSONTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE FISNO = @TMPFISNO AND TIP = @TMPTIP
	
	SELECT @ONCEKIFISNO = MAX(CONVERT(INT, FISNO))
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT, FISNO) < CONVERT(INT, @TMPFISNO) AND TIP = @TMPTIP
	
	SELECT @TMPILKTARIH = TARIH
	FROM TBL_XZ_LOG WITH (NOLOCK)
	WHERE CONVERT(INT,FISNO) = @ONCEKIFISNO AND TIP = @TMPTIP
	
	IF @TMPILKTARIH IS NULL SET @TMPILKTARIH = GETDATE() - 365
END

CREATE TABLE #FISTABLE(ID INT PRIMARY KEY)

IF ISNULL(@NORMALMODE,0) = 0
	INSERT INTO #FISTABLE(ID)
	SELECT ID FROM TBL_FIS_MAIN WITH (NOLOCK)
ELSE
BEGIN
	SELECT FISID INTO #ODEMETABLE FROM TBL_FIS_ODEME WITH (NOLOCK)
	GROUP BY FISID
	HAVING MAX(KREDINO) > 0

	INSERT INTO #FISTABLE(ID)
	SELECT ID FROM TBL_FIS_MAIN WITH (NOLOCK)
	WHERE 
		ID IN (SELECT FISID FROM #ODEMETABLE) OR
		CARIKODU <> '' OR
		TIP > 0

	DROP TABLE #ODEMETABLE
END


SELECT * INTO #FISMAIN FROM TBL_FIS_MAIN WITH (NOLOCK)
WHERE 
	ID IN (SELECT ID FROM #FISTABLE) 

SELECT * INTO #FISDETAY FROM TBL_FIS_DETAY WITH (NOLOCK)
WHERE FISID IN (SELECT ID FROM #FISTABLE)

SELECT * INTO #FISODEME FROM TBL_FIS_ODEME WITH (NOLOCK)
WHERE FISID IN (SELECT ID FROM #FISTABLE)

SELECT * INTO #FISPROMOSYON FROM TBL_FIS_PROMOSYON WITH (NOLOCK)
WHERE FISID IN (SELECT ID FROM #FISTABLE)

DROP TABLE #FISTABLE

SELECT @TMPKUMULATIFTUTAR = 
	SUM(
		CASE 
			WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
			ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
		END 
		) ,
	@TMPKUMULATIFKDV = SUM(
			(
				CASE 
					WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
					ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
				END	
			)  -
			(
				(
					CASE 
						WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 
						ELSE(D.TUTAR-ABS(D.INDTUTAR)) - (ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR))
					END
				) / (1+(KDV / 100.00))		
			)
		) 		
FROM #FISDETAY D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.TIP IN (0,1,8) AND M.KASANO = @TMPKASANO AND M.TARIH <= @TMPSONTARIH

SET @TMPKUMULATIFKDV = ISNULL(@TMPKUMULATIFKDV,0)
SET @TMPKUMULATIFTUTAR = ISNULL(@TMPKUMULATIFTUTAR,0)

CREATE TABLE #RETTABLE(ID INT IDENTITY(1,1) PRIMARY KEY, ACIKLAMA VARCHAR(MAX), TUTAR DECIMAL(21,6), TIP TINYINT)

SELECT
	M.TIP AS BELGETIPI,
	D.*,
	CASE WHEN (M.TUTAR+ABS(M.INDTUTAR)) = 0 THEN 0 ELSE
	(D.TUTAR-ABS(D.INDTUTAR)) -
	(ABS(M.INDTUTAR) / (M.TUTAR+ABS(M.INDTUTAR))) * (D.TUTAR-ABS(D.INDTUTAR)) END AS NETTUTAR
INTO #DETAYTBL
FROM #FISDETAY D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'Z DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM #FISMAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> '' AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-ARŞİV DÖKÜMÜ' ELSE 'FİŞ DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 0
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT CASE WHEN EXISTS(SELECT TOP 1 ID FROM #FISMAIN WITH (NOLOCK) WHERE ISNULL(EFATURAKODU,'') <> ''  AND KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH) THEN 'E-FATURA DÖKÜMÜ' ELSE 'FATURA DÖKÜMÜ' END, 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 1
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İRSALİYE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 8
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İADE DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)

SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM(NETTUTAR) AS TOPLAM,
			SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))) AS TOPKDV,
			SUM(NETTUTAR) - SUM(NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))  AS KDVHRC,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI = 2
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPLAM, TOPKDV, KDVHRC, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'İPTAL DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'BELGE İPTALLERİ ['+CONVERT(VARCHAR, ISNULL(COUNT(*),0))+']', ROUND(ISNULL(SUM(TUTAR),0),2), 2
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP = 3 AND M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İPTALLERİ ['+CONVERT(VARCHAR,COUNT(DISTINCT FISID))+']' ,
	ISNULL(SUM(ABS(TUTAR)),0) AS TUTAR,
	5
FROM #DETAYTBL WITH (NOLOCK)
WHERE BELGETIPI IN (0,1,8) AND TIP = 'IPT'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TOPLAM DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	ACIKLAMA , ROUND(TUTAR,2), 2
FROM (
		SELECT
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00))))) AS TOPKDV,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * (NETTUTAR - (NETTUTAR / (1+(KDV / 100.00)))))  AS KDVHRC,
			SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
			CONVERT(FLOAT,COUNT(DISTINCT FISID)) AS ADET
		FROM #DETAYTBL
		WHERE BELGETIPI IN (0,1,2,8)
	) AS P
UNPIVOT
	(
		TUTAR FOR ACIKLAMA IN (TOPKDV, KDVHRC, TOPLAM, ADET)
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DEPARTMAN DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KSM'+CONVERT(VARCHAR, DEPARTMAN)+' (%'+CONVERT(VARCHAR, KDV)+' KDV)' AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,2,8)
GROUP BY DEPARTMAN, KDV
ORDER BY DEPARTMAN

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN(0,1,8)
GROUP BY KDV
ORDER BY KDV

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'TAHSİLAT DÖKÜMÜ (SATIŞ)', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+ D.KREDITIPI,
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.TUTAR) 
		) AS TUTAR,
	3
FROM #FISODEME D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE M.KASANO = @TMPKASANO AND M.TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND TIP IN(0,1,2,8)
GROUP BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI
ORDER BY '['+CONVERT(VARCHAR, dbo.ZL(KREDINO,2))+'] - '+D.KREDITIPI


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[99] - PUAN',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3
FROM #FISPROMOSYON D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '99'

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[87] - A.V.CEKI',
	SUM(
		CASE WHEN TIP IN (0,1,8) THEN 1 ELSE -1 END *  ABS(D.INDTUTAR) 
		) AS TUTAR,
	3
FROM #FISPROMOSYON D WITH (NOLOCK)
	INNER JOIN #FISMAIN M WITH (NOLOCK) ON M.ID = D.FISID
WHERE 
	M.KASANO = @TMPKASANO AND 
	M.TARIH >= @TMPILKTARIH AND 
	M.TARIH <= @TMPSONTARIH AND 
	TIP IN(0,1,2,8) AND
	D.PROMOSYONTIPI = '87'


DECLARE @TMPTAHSILATTOPLAMI DECIMAL(21,6), @TMPODEMETIPIINDIRIMI DECIMAL(21,6)

SELECT
	@TMPTAHSILATTOPLAMI = SUM(
		TUTAR
		) 
FROM #RETTABLE
WHERE TIP = 3 
 
SELECT @TMPODEMETIPIINDIRIMI = SUM(INDTUTAR)
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'[998] - TAHSİLAT TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0),
	3

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT '[999] - SATIŞ TOPLAMI',
	ISNULL(@TMPTAHSILATTOPLAMI,0) + ISNULL(ABS(@TMPODEMETIPIINDIRIMI),0),
	3

IF EXISTS(
			SELECT TOP 1 ID FROM #FISMAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA GİRİŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
 
IF EXISTS(
			SELECT TOP 1 ID FROM #FISMAIN M WITH (NOLOCK) 
			WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''
		)
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'CARİ KASA ÇIKIŞ DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	CARIADI,
	ABS(TUTAR) AS TUTAR,
	3
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH AND CARIADI <> ''

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'DİĞER BİLGİLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'SATIR İND.TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8) AND INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'ARA TOPLAM İND. ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT 
			SUM(ABS(ABS(F.INDTUTAR) - (ISNULL(P.PTUTAR,0) + ISNULL(U.UTUTAR,0))))  AS TUTAR, 
			COUNT(*) AS ADET 
		FROM #FISMAIN F WITH (NOLOCK)
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS PTUTAR FROM #FISPROMOSYON P WITH (NOLOCK) WHERE ISNULL(KREDINO,0) > 0 GROUP BY FISID) AS P ON P.FISID = F.ID 
			LEFT JOIN (SELECT FISID, SUM(ABS(INDTUTAR)) AS UTUTAR FROM #FISPROMOSYON WITH (NOLOCK) WHERE PROMOSYONTIPI = 99 GROUP BY FISID) AS U ON U.FISID = F.ID 
		WHERE 
			F.KASANO = @TMPKASANO AND 
			F.TARIH >= @TMPILKTARIH AND 
			F.TARIH <= @TMPSONTARIH AND 
			F.TIP IN (0,1,8) AND 
			F.INDTUTAR <> 0
	) AS H

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'ÖDEME TİPİ İND. ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	SUM(INDTUTAR) AS PTUTAR ,
	6
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
ISNULL(KREDINO,0) > 0 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'PUAN HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 99 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'A.V.CEKI HARCAMA ['+CONVERT(VARCHAR, ISNULL(COUNT(DISTINCT FISID),0))+']',
	ISNULL(SUM(INDTUTAR),0) AS PTUTAR ,
	6
FROM #FISPROMOSYON P WITH (NOLOCK) 
WHERE FISID IN (
					SELECT ID FROM #FISMAIN F WITH (NOLOCK)
					WHERE 
						F.KASANO = @TMPKASANO AND 
						F.TARIH >= @TMPILKTARIH AND 
						F.TARIH <= @TMPSONTARIH AND 
						F.TIP IN (0,1,8) AND 
						F.INDTUTAR <> 0
				) AND
PROMOSYONTIPI = 87

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'İNDİRİM TOPLAMI ['+CONVERT(VARCHAR, ISNULL(SUM(ADET),0))+']',
	SUM(TUTAR),
	6
FROM (
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(DISTINCT(FISID)) AS ADET
		FROM #DETAYTBL WITH (NOLOCK)
		WHERE BELGETIPI IN (0,1,8)AND INDTUTAR <> 0
		UNION ALL
		SELECT SUM(ABS(INDTUTAR)) AS TUTAR, COUNT(*) AS ADET FROM #FISMAIN WITH (NOLOCK)
		WHERE KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND TARIH <= @TMPSONTARIH AND TIP IN (0,1,8)AND INDTUTAR <> 0
	) AS H


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA GİRİŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	7
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (4,6) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	'KASA ÇIKIŞ TOPLAMI',
	SUM(ABS(TUTAR)) AS TUTAR,
	8
FROM #FISMAIN M WITH (NOLOCK) 
WHERE M.TIP IN (5,7) AND M.KASANO = @TMPKASANO AND TARIH >= @TMPILKTARIH AND M.TARIH <= @TMPSONTARIH 

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'YEMEK ÇEKİ HARİÇ KDV DÖKÜMÜ', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT
	dbo.SR('%'+CONVERT(VARCHAR, KDV)+' KDV',7)+
	dbo.SL(CONVERT(VARCHAR, CAST(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2) 
									AS MONEY) , 1),10)+' '+
	dbo.SL(CONVERT(VARCHAR, CAST( ABS(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) - 
									(
									ROUND(SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) / 
									(1 + (KDV / 100.00)),2))) 
									AS MONEY) , 1),7)+' '
									
	AS ACIKLAMA,
	SUM((CASE WHEN BELGETIPI = 2 THEN -1 ELSE 1 END) * NETTUTAR) AS TOPLAM,
	2
FROM #DETAYTBL
WHERE BELGETIPI IN (0,1,8) AND FISID NOT IN (SELECT FISID FROM #FISODEME WITH (NOLOCK) WHERE ISTICKET = 1)
GROUP BY KDV
ORDER BY KDV


INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF DEĞERLER', 0, 1

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF KDV', @TMPKUMULATIFKDV, 4
 
INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT 'KÜMÜLATİF TOPLAM', @TMPKUMULATIFTUTAR, 4

INSERT INTO #RETTABLE(ACIKLAMA, TUTAR, TIP)
SELECT dbo.ZL(@TMPKASANO,3)+'/'+@TMPKASIYERKODU+'/'+@TMPKASIYERADI, NULL, 10

UPDATE #RETTABLE
SET TUTAR = NULL
WHERE TIP = 1

SELECT @TMPFISNO AS FISNO, @TMPSONTARIH AS TARIH, * FROM #RETTABLE

DROP TABLE #RETTABLE
DROP TABLE #DETAYTBL
DROP TABLE #FISMAIN
DROP TABLE #FISDETAY
DROP TABLE #FISODEME
DROP TABLE #FISPROMOSYON
GO

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('dbo.TBL_STOK_MAIN') AND name='MIKTARLISATISYAPILAMAZ')
ALTER TABLE dbo.TBL_STOK_MAIN ADD
	MIKTARLISATISYAPILAMAZ bit NULL
GO

ALTER PROCEDURE [dbo].[SP_IMPORT_URUN_FILE]
	@ISDEGISEN BIT = 0,
	@ISTRUNCATETABLE BIT = 1
AS

SET NOCOUNT ON

DECLARE
	@ERRORMESSAGE NVARCHAR(MAX)
CREATE TABLE #TEMPFILE(
						PLUNO INT, 
						BARKOD VARCHAR(20), 
						STOKADI VARCHAR(50), 
						FIYAT FLOAT, 
						DEPARTMAN INT,
						BIRIM VARCHAR(4),
						TARTILI VARCHAR(1),
						FIYAT2 FLOAT,
						FIYAT3 FLOAT,
						DOVIZKODU VARCHAR(10),
						ALISDEPARTMAN INT,
						STOKKODU VARCHAR(20),
						REYONADI VARCHAR(20),
						RENK VARCHAR(50),
						BEDEN VARCHAR(20),
						MODELKODU VARCHAR(20),
						TEVKIFATKODU VARCHAR(10),
						TEVKIFATACIKLAMA VARCHAR(100),
						TEVKIFATORANI INT,
						OTVKODU VARCHAR(10),
						OTVACIKLAMA VARCHAR(100),
						OTVORANI INT,
						ALISFIYAT FLOAT,
						ISINDIRIM BIT,
						MIKTARLISATISYAPILAMAZ BIT
					)
BEGIN TRY
	
--IF EXISTS(
--				SELECT TOP 1 1 FROM TBL_IMPORT_FILE 
--				WHERE PATINDEX('%[Ã‡]%', DATA COLLATE Latin1_General_bin) > 0
--			)
--	UPDATE TBL_IMPORT_FILE
--	SET DATA = dbo.utf8_to_utf16(DATA)

	DECLARE @DATA VARCHAR(MAX)

	SELECT TOP 1 @DATA = DATA FROM TBL_IMPORT_FILE
	
	IF LEN(@DATA) <= 82
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM, MIKTARLISATISYAPILAMAZ)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,20)) AS STOKADI,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,10),'.',''))/100 
			ELSE CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,48,9),'.',''))/100 END AS FIYAT,
			CASE WHEN LEN(DATA) = 65 THEN 
			CONVERT(INT, SUBSTRING(DATA,58,2)) 
			ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS DEPARTMAN,
			CASE WHEN LEN(DATA) = 65 THEN 
				RTRIM(SUBSTRING(DATA,60,4)) 
			ELSE
				RTRIM(SUBSTRING(DATA,59,4)) END AS BIRIM,
			
			CASE WHEN LEN(DATA) = 65 THEN 
				SUBSTRING(DATA,64,1)
			ELSE
				SUBSTRING(DATA,63,1) END AS TARTILI,
			0 AS FIYAT2,
			0 AS FIYAT3,
			'TL' AS DOVIZKODU,
			CASE WHEN LEN(DATA) = 65 THEN CONVERT(INT, SUBSTRING(DATA,58,2)) ELSE CONVERT(INT, SUBSTRING(DATA,57,2)) END AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,8,20)) AS STOKKODU,
			'' AS REYONADI,
			'' AS RENK,
			'' AS BEDEN,
			'' AS MODELKODU,
			'' AS TEVKIFATKODU,
			'' AS TEVKIFATACIKLAMA,
			0  AS TEVKIFATORANI,
			'' AS OTVKODU,
			'' AS OTVACIKLAMA,
			0  AS OTVORANI,
			0 AS ALISFIYAT,
			1 AS ISINDIRIM,
			0 AS MIKTARLISATISYAPILAMAZ
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63 AND LEN(@DATA) = LEN(DATA)
	ELSE
		INSERT INTO #TEMPFILE(PLUNO, BARKOD, STOKADI, FIYAT, DEPARTMAN, BIRIM, TARTILI, FIYAT2, FIYAT3, DOVIZKODU, ALISDEPARTMAN, STOKKODU, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM, MIKTARLISATISYAPILAMAZ)
		SELECT
			CONVERT(INT, SUBSTRING(DATA,2,6)) AS PLUNO,
			RTRIM(SUBSTRING(DATA,8,20)) AS BARKOD,
			RTRIM(SUBSTRING(DATA,28,50)) AS STOKADI,
			CONVERT(FLOAT, REPLACE(SUBSTRING(DATA,78,9),'.',''))/100 AS FIYAT,
			CONVERT(INT, SUBSTRING(DATA,87,2)) AS DEPARTMAN,
			RTRIM(SUBSTRING(DATA,89,4)) AS BIRIM,
			SUBSTRING(DATA,93,1) AS TARTILI,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,94,9),'.',''),'0')) / 100 AS FIYAT2,
			CONVERT(FLOAT, ISNULL(REPLACE(SUBSTRING(DATA,103,9),'.',''),'0')) / 100 AS FIYAT3,
			RTRIM(SUBSTRING(DATA,112,10)) AS DOVIZKODU,
			CONVERT(INT, SUBSTRING(DATA,122,2)) AS ALISDEPARTMAN,
			RTRIM(SUBSTRING(DATA,124,20)) AS STOKKODU,
			RTRIM(SUBSTRING(DATA,144,20)) AS REYONADI,
			RTRIM(SUBSTRING(DATA,164,50)) AS RENK,
			RTRIM(SUBSTRING(DATA,214,20)) AS BEDEN,
			RTRIM(SUBSTRING(DATA,234,20)) AS MODELKODU,
			RTRIM(SUBSTRING(DATA,254,10)) AS TEVKIFATKODU,
			RTRIM(SUBSTRING(DATA,264,100)) AS TEVKIFATACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,364,3)) AS TEVKIFATORANI,
			RTRIM(SUBSTRING(DATA,367,10)) AS OTVKODU,
			RTRIM(SUBSTRING(DATA,377,100)) AS OTVACIKLAMA,
			CONVERT(INT, SUBSTRING(DATA,477,3)) AS OTVORANI,
			CONVERT(FLOAT, ISNULL(REPLACE(REPLACE(REPLACE(SUBSTRING(DATA,480,9),'.',''),CHAR(13),'0'),CHAR(10),'0'),'0'))/100 AS ALISFIYAT,
			CONVERT(BIT, CASE WHEN SUBSTRING(DATA,489,1) = '0' THEN 0 ELSE 1 END) AS ISINDIRIM,
			CONVERT(BIT, CASE WHEN SUBSTRING(DATA,490,1) = '1' THEN 1 ELSE 0 END) AS MIKTARLISATISYAPILAMAZ
		FROM TBL_IMPORT_FILE
		WHERE LEN(DATA) >= 63  AND LEN(@DATA) = LEN(DATA)
END TRY
BEGIN CATCH
	SET @ERRORMESSAGE = 'HATA : ÜRÜN DOSYASININ PARSE EDİLMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END CATCH

DELETE FROM #TEMPFILE
WHERE BARKOD IN (
                                                SELECT BARKOD FROM #TEMPFILE
                                                GROUP BY BARKOD
                                                HAVING COUNT(*) > 1
                                        )

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE),0) <= 0
BEGIN
	SET @ERRORMESSAGE = 'HATA : URUN DOSYASI BOS GÖNDERİLEMEZ'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

DECLARE @DEPARTMAN INT

SELECT TOP 1 @DEPARTMAN = DEPARTMAN
FROM #TEMPFILE
WHERE DEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU DEPARTMAN TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

SET @DEPARTMAN = NULL

SELECT TOP 1 @DEPARTMAN = ALISDEPARTMAN
FROM #TEMPFILE
WHERE ALISDEPARTMAN NOT IN (SELECT DEPARTMAN FROM TBL_DEPARTMAN WITH (NOLOCK))

IF @DEPARTMAN IS NOT NULL
BEGIN
	SET @ERRORMESSAGE = 'HATA : '+CONVERT(VARCHAR, @DEPARTMAN)+' NOLU ALIŞ DEPARTMANI TANIMLI DEĞİL!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

IF ISNULL((SELECT COUNT(*) FROM #TEMPFILE WHERE PLUNO = 0),0) > 1
BEGIN
	SET @ERRORMESSAGE = 'HATA : PLU NUMARASI SIFIR OLAN ÜRÜNLER MEVCUT.!'
	RAISERROR(@ERRORMESSAGE,16,1)
	RETURN
END

CREATE TABLE #TMPREYON(PLUNO INT, REYONADI VARCHAR(20))

IF LEN(@DATA) <= 80
	INSERT INTO #TMPREYON(PLUNO, REYONADI)
	SELECT PLUNO, REYONADI FROM TBL_STOK_MAIN WITH (NOLOCK)
	GROUP BY PLUNO, REYONADI

BEGIN TRAN

	IF @ISDEGISEN = 1
	BEGIN
		BEGIN TRY
			DELETE FROM TBL_STOK_MAIN
			WHERE PLUNO IN (SELECT PLUNO FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH

		BEGIN TRY
			DELETE FROM TBL_STOK_MAIN
			WHERE BARKOD IN (SELECT BARKOD FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK MAIN TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH

		BEGIN TRY
			DELETE FROM TBL_STOK_KOD
			WHERE BARKOD IN (SELECT BARKOD FROM #TEMPFILE)
		END TRY
		BEGIN CATCH
			DROP TABLE #TEMPFILE
			DROP TABLE #TMPREYON
			ROLLBACK TRANSACTION
			SET @ERRORMESSAGE = 'HATA : STOK KOD TABLOSUNDAN KAYIT SİLİNMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
			RAISERROR(@ERRORMESSAGE,16,1)
			RETURN
		END CATCH
	END
	ELSE
	BEGIN
		IF ISNULL(@ISTRUNCATETABLE,1) = 1
		BEGIN
			TRUNCATE TABLE TBL_STOK_MAIN
			TRUNCATE TABLE TBL_STOK_KOD
		END
	END

	BEGIN TRY
		INSERT INTO TBL_STOK_MAIN(PLUNO, BARKOD, STOKADI, DEPARTMAN, KDV, BIRIM, FIYAT, FIYAT2, FIYAT3, TARTILI, CREATEDATE, CREATEUSERCODE, DOVIZKODU, ALISDEPARTMAN, ALISKDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM, MIKTARLISATISYAPILAMAZ)
		SELECT T.PLUNO, T.BARKOD, T.STOKADI, T.DEPARTMAN, D.KDV, T.BIRIM, T.FIYAT, CASE WHEN ISNULL(T.FIYAT2,0) = 0 THEN T.FIYAT ELSE T.FIYAT2 END, CASE WHEN ISNULL(T.FIYAT3,0) = 0 THEN T.FIYAT ELSE T.FIYAT3 END, T.TARTILI, GETDATE(), APP_NAME(), DOVIZKODU, T.ALISDEPARTMAN, A.KDV, REYONADI, RENK, BEDEN, MODELKODU, TEVKIFATKODU, TEVKIFATACIKLAMA, TEVKIFATORANI, OTVKODU, OTVACIKLAMA, OTVORANI, ALISFIYAT, ISINDIRIM, MIKTARLISATISYAPILAMAZ FROM #TEMPFILE T
			INNER JOIN TBL_DEPARTMAN D WITH (NOLOCK) ON D.DEPARTMAN = T.DEPARTMAN
			INNER JOIN TBL_DEPARTMAN A WITH (NOLOCK) ON A.DEPARTMAN = T.ALISDEPARTMAN
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	BEGIN TRY
		SELECT BARKOD, STOKKODU, CONVERT(BIT,0) AS ISDELETE INTO #STOKKOD FROM #TEMPFILE
		GROUP BY BARKOD, STOKKODU

		UPDATE #STOKKOD
		SET ISDELETE = 1
		FROM #STOKKOD S
			INNER JOIN TBL_STOK_KOD K WITH (NOLOCK) ON K.BARKOD = S.BARKOD 

		INSERT INTO TBL_STOK_KOD(BARKOD, STOKKODU)
		SELECT BARKOD, STOKKODU FROM #STOKKOD
		WHERE ISDELETE = 0
		GROUP BY BARKOD, STOKKODU
	END TRY
	BEGIN CATCH
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENMESİ SIRASINDA HATA : '+ERROR_MESSAGE()
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END CATCH
	
	IF LEN(@DATA) <= 80
		UPDATE TBL_STOK_MAIN 
		SET REYONADI = R.REYONADI
		FROM TBL_STOK_MAIN S
			INNER JOIN #TMPREYON R ON R.PLUNO = S.PLUNO	
	
	IF ISNULL((SELECT COUNT(*) FROM TBL_STOK_MAIN WITH (NOLOCK)),0) <= 0
	BEGIN
		DROP TABLE #TEMPFILE
		DROP TABLE #TMPREYON
		ROLLBACK TRANSACTION
		SET @ERRORMESSAGE = 'HATA : TBL_STOK_MAIN TABLOSUNA KAYIT EKLENEMEDİ'
		RAISERROR(@ERRORMESSAGE,16,1)
		RETURN
	END
	
DROP TABLE #TEMPFILE
DROP TABLE #TMPREYON

COMMIT TRAN
GO

ALTER PROCEDURE [dbo].[SP_STOK_MAIN_LIST]
	@BARKOD VARCHAR(20) = NULL,
	@PLUNO INT = NULL
AS
	IF @BARKOD IS NOT NULL
		SELECT
			S.ID,
			S.PLUNO,
			S.BARKOD,
			S.STOKKODU,
			S.STOKADI,
			S.DEPARTMAN,
			S.KDV,
			S.BIRIM,
			S.FIYAT,
			S.FIYAT2,
			S.FIYAT3,
			CASE WHEN D.ID IS NULL THEN 'TL' ELSE ISNULL(S.DOVIZKODU,'TL') END AS DOVIZKODU, 
			CASE WHEN ISNULL(D.DOVIZKURU,1) = 0 THEN 1 ELSE ISNULL(D.DOVIZKURU,1) END DOVIZKURU,
			S.TARTILI,
			S.CREATEDATE,
			S.CREATEUSERCODE,
			S.ALISDEPARTMAN,
			S.ALISKDV,
			S.RENK,
			S.BEDEN,
			S.MODELKODU,
			S.TEVKIFATKODU,
			S.TEVKIFATACIKLAMA,
			S.TEVKIFATORANI,
			S.OTVKODU,
			S.OTVACIKLAMA,
			S.OTVORANI,
			S.ISINDIRIM,
			ISNULL(MIKTARLISATISYAPILAMAZ,0) AS MIKTARLISATISYAPILAMAZ
		FROM TBL_STOK_MAIN S WITH (NOLOCK)
			LEFT JOIN TBL_DOVIZ D WITH (NOLOCK) ON D.DOVIZKODU = S.DOVIZKODU
		WHERE S.BARKOD = @BARKOD
	ELSE
		SELECT
			S.ID,
			S.PLUNO,
			S.BARKOD,
			S.STOKKODU,
			S.STOKADI,
			S.DEPARTMAN,
			S.KDV,
			S.BIRIM,
			S.FIYAT,
			S.FIYAT2,
			S.FIYAT3,
			CASE WHEN D.ID IS NULL THEN 'TL' ELSE ISNULL(S.DOVIZKODU,'TL') END AS DOVIZKODU, 
			CASE WHEN ISNULL(D.DOVIZKURU,1) = 0 THEN 1 ELSE ISNULL(D.DOVIZKURU,1) END DOVIZKURU,
			S.TARTILI,
			S.CREATEDATE,
			S.CREATEUSERCODE,
			S.ALISDEPARTMAN,
			S.ALISKDV,
			S.RENK,
			S.BEDEN,
			S.MODELKODU,
			S.TEVKIFATKODU,
			S.TEVKIFATACIKLAMA,
			S.TEVKIFATORANI,
			S.OTVKODU,
			S.OTVACIKLAMA,
			S.OTVORANI,
			S.ISINDIRIM,
			ISNULL(MIKTARLISATISYAPILAMAZ,0) AS MIKTARLISATISYAPILAMAZ
		FROM TBL_STOK_MAIN S WITH (NOLOCK)
			LEFT JOIN TBL_DOVIZ D WITH (NOLOCK) ON D.DOVIZKODU = S.DOVIZKODU
		WHERE S.PLUNO = @PLUNO
GO
